从 List<Integer> 中正确删除整数 [英] Properly removing an Integer from a List<Integer>
问题描述
这是我刚刚遇到的一个不错的陷阱.考虑一个整数列表:
Here's a nice pitfall I just encountered. Consider a list of integers:
List<Integer> list = new ArrayList<Integer>();
list.add(5);
list.add(6);
list.add(7);
list.add(1);
对执行 list.remove(1)
时会发生什么的任何有根据的猜测?list.remove(new Integer(1))
怎么样?这可能会导致一些令人讨厌的错误.
Any educated guess on what happens when you execute list.remove(1)
? What about list.remove(new Integer(1))
? This can cause some nasty bugs.
区分 remove(int index)
,从给定的索引和 remove(Object o)
,通过参考,在处理整数列表时?
What is the proper way to differentiate between remove(int index)
, which removes an element from given index and remove(Object o)
, which removes an element by reference, when dealing with lists of integers?
这里要考虑的要点是@Nikita提到 - 精确参数匹配优先于自动装箱.
The main point to consider here is the one @Nikita mentioned - exact parameter matching takes precedence over auto-boxing.
推荐答案
Java 总是调用最适合您的论点的方法.自动装箱和隐式向上转换仅在没有可以在没有转换/自动装箱的情况下调用的方法时执行.
Java always calls the method that best suits your argument. Auto boxing and implicit upcasting is only performed if there's no method which can be called without casting / auto boxing.
List 接口指定了两个 remove 方法(请注意参数的命名):
The List interface specifies two remove methods (please note the naming of the arguments):
remove(Object o)
remove(int index)
这意味着 list.remove(1)
删除位置 1 处的对象,remove(new Integer(1))
从这份清单.
That means that list.remove(1)
removes the object at position 1 and remove(new Integer(1))
removes the first occurrence of the specified element from this list.
这篇关于从 List<Integer> 中正确删除整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!