从ArrayList中删除项目时出错 [英] Error removing an item from an ArrayList
问题描述
我正在尝试使用线程从列表中删除一个值.但是代码失败并给出异常.请帮助我是线程编程的初学者.....
I'm trying to remove a value from the list using thread. But the code fails and gives an exception. Plz help I'm a beginner in thread programming.....
这是Test.java
import java.util.*;
public class Test {
private static final List<Integer> Values = new ArrayList<Integer> ();
public static void main(String args[]) {
TestThread t1 = new TestThread(Values);
t1.start();
System.out.println(Values.size());
}
}
这是TestThread.java
import java.util.*;
public class TestThread extends Thread {
private final List<Integer> Values;
public TestThread(List<Integer> v) {
this.Values = v;
Values.add(5);
}
public void run() {
Values.remove(5);
System.out.println("5 removed");
}
}
推荐答案
此行的意思是:删除索引5处的值.但是索引5没有任何内容.
This line means: remove the value at index 5. But there's nothing in index 5.
Values.remove(5);
当前数组中只有1个值,因为此行表示将值5添加到我的列表中,而不是将5个值添加到我的列表中.
There's only 1 value in the array currently because this line means add the value 5 into my list, not add 5 values to my list.
Values.add(5);
您的错误很可能是IndexOutOfBoundsException
.如果显示列表的大小,您会更清楚地看到它.
Your error is most likely IndexOutOfBoundsException
. You'll see it more clearly if you display the size of your list.
public void run() {
System.out.println(Values.size()); // should give you 1
Values.remove(5);
System.out.println("5 removed");
}
这是它的外观:
插入时,将5个自动装箱到Integer对象中.因此,要成功删除它,应将其包装为一个:new Integer(5)
.然后发出删除呼叫.然后,它将调用接受对象而不是int的remove的重载版本.
When it was inserted, 5 got auto-boxed into an Integer object. Thus, to successfully remove it, you should wrap it into one: new Integer(5)
. Then issue the remove call. It will then invoke the overloaded version of remove that accepts an Object, instead of the int.
Values.remove(new Integer(5));
表示从我的列表中删除名为"5"的Integer对象.
means Remove the Integer object named '5' from my list.
这篇关于从ArrayList中删除项目时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!