2015-12-29 76 views
0

我有一个简单的循环在字符串数组,然后将字符串传递给threadlist方法。不过,我似乎无法打印出两个字符串。它只是打印第二个名字"Fred",这使我认为我用第二个字符串覆盖了第一个字符串。我如何使ArrayList包括字符串"Tim""Fred"循环线程arraylist

import java.util.ArrayList; 

public class Threads extends Thread implements Runnable{ 

    private ArrayList threadList; 
    private String e; 

    public static void main(String[] args) { 
     String[] elements = {"Tim","Fred"};  
     Threads t = new Threads(); 
     for (String e: elements) {   
      t.threadL(e); 
     } 
     //loop over the elements of the String array and on each loop pass the String to threadL 

     for (int index = 0;index<t.threadList.size();index++){ 
      System.out.print(t.threadList.get(index)); 
     } 
     //loop over the threadList arraylist and printout 
    } 

    public ArrayList<String> threadL(String e) { 
     threadList = new ArrayList<>(); 
     threadList.add(e); 
     return(threadList); 
    } 
} 
+2

'threadList = new ArrayList <>();'你在这里发生了什么?特别是当你第二次调用'threadL'时? – Tom

+2

你在哪里实现Runnable? – Untitled123

+0

每次调用'threadL'时,您都在创建一个新的'ArrayList'。 –

回答

5

直接解决您的问题是,你的方法threadL被调用threadList变量每次实例。因此,在第二个电话,无论是之前存储被忽略,并加入新的内容:

public ArrayList<String> threadL(String e) { 
    threadList = new ArrayList<>(); // <-- instantiates a new list each time it is called 
    threadList.add(e); 
    return threadList; 
} 

您应该实例该名单只有一次,例如在声明。此外,你绝对不应该使用原始类型,如List但总是类型版本:

private List<String> threadList = new ArrayList<>(); 

注意,在给定的例子,你实际上是不使用任何ThreadRunnable功能(因为你没有覆盖run()或启动线程)。另外,prefer implementing Runnable over extending Thread

+0

谢谢你,我删除了threadList = new ArrayList <>();并声明私人列表 threadList = new ArrayList <>();原来 – Ingram

0

您每次执行循环时都会实例化一个新的数组列表。这就是为什么你看不到元素[0],因为它被替换为新列表。