0

I have a simple loop over a String array which then passes the String to a threadlist method. However I can't seem to print out both String's. It just prints the second name "Fred" which makes me think that I am overwriting the first String with the second String. How can I make the ArrayList include both Strings "Tim" and "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);
    }
}
Tunaki
  • 132,869
  • 46
  • 340
  • 423
Ingram
  • 654
  • 2
  • 7
  • 29

2 Answers2

5

The direct solution to your problem is that you are instantiating the threadList variable each time the method threadL is invoked. So on the second call, whatever was stored before is disregarded and the new content is added:

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

You should instantiate that list only once, for example where it is declared. Also, you definitely should not use raw types like List but always the typed version:

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

Note that in the given example, you are actually not using any Thread or Runnable feature (since you did not override run() or started the thread). Also, prefer implementing Runnable over extending Thread.

Community
  • 1
  • 1
Tunaki
  • 132,869
  • 46
  • 340
  • 423
  • Thanks for this, i removed threadList = new ArrayList<>(); and declared private List threadList = new ArrayList<>(); initially – Ingram Dec 29 '15 at 22:07
0

You are instantiating a new array list each time you go through loop. That's why you can't see element[0], since it's replaced with new list.