我有一個簡單的循環在字符串數組,然後將字符串傳遞給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);
}
}
'threadList = new ArrayList <>();'你在這裏發生了什麼?特別是當你第二次調用'threadL'時? – Tom
你在哪裏實現Runnable? – Untitled123
每次調用'threadL'時,您都在創建一個新的'ArrayList'。 –