循环线程arraylist

Ing*_*ram 0 java arrays arraylist

我在String数组上有一个简单的循环,然后将String传递给threadlist方法.但是我似乎无法打印出两个String.它只打印第二个名称"Fred",这让我觉得我用第二个String覆盖了第一个String.我怎样才能ArrayList包括字符串"Tim""Fred"

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Tun*_*aki 5

您的问题的直接解决方案是threadList每次threadL调用方法时都要实例化变量.因此,在第二次调用时,忽略之前存储的内容并添加新内容:

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

您应该只将该列表实例化一次,例如声明它的位置.此外,你绝对不应该使用原始类型,List但始终使用键入的版本:

private List<String> threadList = new ArrayList<>();
Run Code Online (Sandbox Code Playgroud)

请注意,在给定的示例中,您实际上没有使用任何ThreadRunnable功能(因为您没有覆盖run()或启动线程).此外,更喜欢实施Runnable过度扩展Thread.