2013-04-07 86 views
2

我试图从线程列表中删除一个值。但是代码失败并给出一个例外。 plz帮助我在线程编程初学者.....从ArrayList删除项目时出错

这是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"); 
    } 
} 
+0

什么是错误? – BobTheBuilder 2013-04-07 06:43:55

+0

什么是异常,是什么原因造成的? – drewmoore 2013-04-07 06:43:59

+0

1Exception在线程 “线程0” java.lang.IndexOutOfBoundsException:指数:5,大小:1 \t在java.util.ArrayList.rangeCheck(ArrayList.java:603) \t在java.util.ArrayList.remove (ArrayList.java:444) \t at TestThread.run(TestThread.java:12) – khirod 2013-04-07 06:45:27

回答

3

这条线是指:在索引5删除值。但是,有没有在指数5

Values.remove(5); 

,因为这条线意味着增加值5到我的列表,而不是增加5个值进入我的列表有1只目前在数组中值。

Values.add(5); 

您的错误很可能是IndexOutOfBoundsException。如果显示列表的大小,您会更清楚地看到它。

public void run() { 
    System.out.println(Values.size()); // should give you 1 
    Values.remove(5); 
    System.out.println("5 removed"); 
} 

这是它的外观:

enter image description here

当它被插入,5得到自动装箱成Integer对象。因此,要成功删除它,你应该将它包装成一个:new Integer(5)。然后发出删除呼叫。然后它将调用接受Object的remove的重载版本,而不是int。

Values.remove(new Integer(5)); 

手段取下我的名单命名为 '5' 的Integer对象。

+1

+1为好解释:) – Maroun 2013-04-07 06:57:46

1

您的来电Values.remove(5); ISN内容不要做你期望的事情。你在参数中传递的int是一个索引值,所以它试图删除你的数组列表中的索引5处的项目,但其中只有1个值。

一种解决方法,使你删除一给定值

int given = 5; 
for (int curr = 0; curr < Values.size(); curr++){ 
    if (Values.get(curr) == given) { 
     Values.remove(given); 
    } 
} 
2

List#remove(int)方法在从列表中指定位置移除元件的一个整数,所以Values.remove(5)将尝试在索引5元件,其元件确实以除去在那里存在。这里int值5不会自动装箱,因为List#remove(int)已经存在。

您应该使用List#remove(Object o)其中实际上Values.remove(new Integer(5))

public void run() { 
    Values.remove(new integer(5)); 
    System.out.println("5 removed"); 
} 
+0

欢迎您:) :) – 2013-04-07 06:52:59

1

List (ArrayList)有2种remove方法(过载)

  1. remove(int) - >这意味着在索引中删除
  2. remove(Object) - >这意味着从列表中删除所述特定对象

当您说Values.remove(5)时,编译器将5作为int并调用remove(int)方法,该方法试图在索引5.自索引5,dint有任何值,IndexOutOfBoundException被抛出。

要解决它,比如说remove(new Integer(5)),要编译器,调用remove(Object)方法。 为了更加清晰,请参阅SO thread