2015-12-29 109 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],因爲它被替換爲新列表。