gpt4 book ai didi

java - 是否有任何完全通用的 Map.get() 版本,即 "V get(K key)"

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:11:00 31 4
gpt4 key购买 nike

由于 Map.get() 不是完全通用的,我们经常发现开发人员传递不同类型的对象(因此存在错误)的情况。当我们开始使用其他团队的工件/服务时,这种情况的发生频率就会上升。 What are the reasons why Map.get(Object key) is not (fully) generic解释了为什么 get() 不是完全通用的。

由于我们实际上并没有属于不同类型但“语义上”相等的两个对象的用例,因此拥有一个版本的 Map.get() 确实可以帮助我们在编译时识别此类错误。是否存在可用于生产的 API?

最佳答案

这不是您问题的直接答案,但某些 IDE(至少是 IntelliJ)会进行检查以标记对集合的可疑使用,这肯定会被它捕获:

Map<String, Integer> map = new HashMap<String, Integer>();
map.put("hello", 5);

//In IntelliJ, this line gives the warning:
//Map<String, Integer> may not contain objects of type StringBuilder
System.out.println(map.get(new StringBuilder("hello")));

您提到您试图在编译时发现这些问题,所以我认为值得一提。您可以将其与构建服务器的静态分析工具配对,例如 findbugs。

在 IntelliJ 中,检查称为“可疑集合方法调用”。

编辑 (2011/10/18)

在 FindBugs 中,错误似乎是 GC_UNRELATED_TYPES应该捕获这个(虽然我没有尝试测试这个):

GC: No relationship between generic parameter and method argument

This call to a generic collection method contains an argument with an incompatible class from that of the collection's parameter (i.e., the type of the argument is neither a supertype nor a subtype of the corresponding generic type argument). Therefore, it is unlikely that the collection contains any objects that are equal to the method argument used here. Most likely, the wrong value is being passed to the method. (...)

关于java - 是否有任何完全通用的 Map.get() 版本,即 "V get(K key)",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7418680/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com