区分ArrayList #remove()方法

时间:2014-02-16 22:53:10

标签: java arraylist indexing indexoutofboundsexception

我有一个整数的ArrayList;

ArrayList<Integer> list = new ArrayList<>();
list.add(8);
list.add(20);
list.add(50);

我还有一个变量,它被设置为该ArrayList中的随机项。我想从arraylist中删除变量中的项目,所以我尝试了这个;

list.remove(var);

但是,它假定因为var是一个整数,它会尝试在var的位置获取索引,而不是搜索和删除它。但是因为列表中的每个项都大于它的大小,所以它总是给出一个ArrayOutOfBoundsException。有没有办法强制Java尝试使用正确的删除方法?

2 个答案:

答案 0 :(得分:3)

您需要传递Integer - 您的主要选项是:

Integer valueToRemove = 8;
list.remove(valueToRemove);

int anotherOne = 20;
list.remove(Integer.valueOf(anotherOne));

int andFinally = 50;
list.remove((Integer) andFinally);

答案 1 :(得分:2)

当你调用add(8)时,它实际上是自动装箱的,因此实际的调用是add(new Integer(8))。在remove()调用中不会发生这种情况,因为实际上有一个remove()调用将int作为参数。解决方案是自己创建Integer对象,而不是依赖于自动装箱:list.remove(new Integer(var))