Java 为什么短对象列表不能检查是否包含该值
我才刚开始学习收藏。 当我尝试检查之前添加的值5是否存在时,它总是返回falseJava 为什么短对象列表不能检查是否包含该值,java,arraylist,collections,Java,Arraylist,Collections,我才刚开始学习收藏。 当我尝试检查之前添加的值5是否存在时,它总是返回false List<Short> shortList = new ArrayList<>(); shortList.add((short) 5); System.out.println(shortList.contains(5)); List shortList=new ArrayList(); 短名单。增加((短)5); System.out.println(shortList.contains(
List<Short> shortList = new ArrayList<>();
shortList.add((short) 5);
System.out.println(shortList.contains(5));
List shortList=new ArrayList();
短名单。增加((短)5);
System.out.println(shortList.contains(5));
输出:
假的
我不明白这到底是怎么回事?这是一个非常普遍的逻辑。几年前我也遇到过同样的问题。这就是我当时发现的 简短回答: 由于自动装箱,值5转换为整数对象。 当ArrayList检查值时,它会将每个对象与.equals()运算符和.equals of Integer进行比较,仅当两个对象的类型相同时,Short才会继续比较它们的基本值(.intValue或.shortValue) 长答案: 执行短名单时。包含(5) 发生以下情况:
Integer.valueOf(int) line: 830
因为这里的对象“obj”是“Short”类型,instanceof操作符失败,导致输出为false。这是从哪里复制的?@Idos我在一个文件中保存了一份堆栈跟踪和代码片段的副本,从那里复制。@BandiKishore为什么Integer类的实现不能直接检查基元值,而不是同时检查类型?
public int indexOf(Object o) {
...
// Here Object "o" is of Type Integer in your case, So It calls Integer.equals
if (o.equals(elementData[i]))
...
// If not equal or not found.
return -1;
}
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}