Java中ArrayList remove()的不良行为 [英] Undesired behavior of ArrayList remove() in Java
问题描述
我有以下两种情况:
1。 int值作为参数
int intNum = 2;
List< Integer> list = new ArrayList< Integer>();
list.add(1);
list.add(2);
list.add(3);
list.remove(intNum);
System.out.println(list.size());
//输出:2
2。长值作为参数
long longNum = 2;
List< Integer> list = new ArrayList< Integer>();
list.add(1);
list.add(2);
list.add(3);
list.remove(longNum);
System.out.println(list.size());
//输出:3
在两种情况下,我都将2作为值传递,但是我得到列表的其他大小值。此行为的真正原因是什么?
从列表中正确删除整数不能解释内置数据类型具有相同的值,但行为与上面要求的不同
自动装箱
list.remove
方法已重载,并且两个不同的签名用于不同的目的。一个 list.remove(int)
根据其索引删除一个项目,另一个 list.remove(Object)
,基于对象相等性删除一个项目。
第一种情况触发第一种类型,第二种情况(带有 long longNum
)触发第二种类型,将 long自动装箱
原语到 java.lang.Long
对象。这不等于添加到列表中的 java.lang.Integer
(自动装箱)值,因此不会从列表中删除任何内容,并且大小将保持不变。 / p>
I have following two scenarios:
1. int value as parameter
int intNum = 2;
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.remove(intNum);
System.out.println(list.size());
// output: 2
2. long value as parameter
long longNum = 2;
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.remove(longNum);
System.out.println(list.size());
// output: 3
I am passing 2 as the value in both cases, but I am getting a different size value of the List. What is the actual reason for this behavior?
Properly removing an Integer from a List does not explain about build-in data type having same value but having behavior differently as asked above
Autoboxing
The list.remove
method is overloaded, and the two different signatures are used for different purposes. One, list.remove(int)
, removes an item based on its index, and the other one, list.remove(Object)
, removes an item based on object equality.
Your first situation triggers the first type, and your second example (with a long longNum
), triggers the second type, autoboxing the long
primitive to a java.lang.Long
object. This is not equal to the java.lang.Integer
(autoboxed) values added to the list, and thus will not remove anything from the list and the size will remain same.
这篇关于Java中ArrayList remove()的不良行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!