Java ArrayList.remove()问题

use*_*316 16 java

这是我的代码的一部分.

Integer keyLocation = reducedFD.indexOf(KeyPlus.get(KEYindex));
someArrayList.remove(keyLocation);
Run Code Online (Sandbox Code Playgroud)

所以我在这里做的是我分配keyLocation(reduceFD arrayList中第一个出现的字符串).但是当我想从someArrayList中删除具有该keyLocation的项时,它将无法工作.

如果我手动输入:

someArrayList.remove(0); //Let's say 0 is the actual keyLocation
Run Code Online (Sandbox Code Playgroud)

这实际上有效.

有什么奇怪的是下面的代码也可以工作:

someArrayList.remove(keyLocation + 1);
Run Code Online (Sandbox Code Playgroud)

任何提示?

这是主循环:

for (int KEYindex = 0; KEYindex < KeyPlus.size(); KEYindex++){

 Integer keyLocation = reducedFD.indexOf(KeyPlus.get(KEYindex));

if (reducedFD.contains(KeyPlus.get(KEYindex))){

 KeyPlus.add(reducedFD.get(keyLocation+1));
 CheckedAttributesPlus.add(KeyPlus.get(KEYindex));
 reducedFD.remove(keyLocation);

}
}
Run Code Online (Sandbox Code Playgroud)

MeB*_*Guy 81

问题是您将Integer传递给remove方法,而不是int.传递整数时,它假定整数本身就是您要删除的内容,而不是该索引处的值.比较方法

remove(Object o)
remove(int i)
Run Code Online (Sandbox Code Playgroud)

所以:

int keyLocation = reducedFD.indexOf(KeyPlus.get(KEYindex));
someArrayList.remove(keyLocation);
Run Code Online (Sandbox Code Playgroud)

  • 那飞过我的脑袋.非常感谢. (5认同)

小智 14

这是简短的描述:

remove(Object o) // remove object
remove(int index) // remove the object in that index
Run Code Online (Sandbox Code Playgroud)

如果您编写.remove(5)编译器将其理解为基本类型以及索引并删除index(5).如果要删除对象,则应编写.remove(new Integer(5))