0

I'm trying to add Objects ( in this example to keep it simple Strings) to Arraylists, that are collected as an Arraylist. Here is the code:

    public static void main(String[] args) {
    ArrayList dummylist = new ArrayList();
    ArrayList<ArrayList<String>> dummylistlist = new ArrayList<ArrayList<String>>();

    for (int j=0; j< 2; j++){
      dummylistlist.add(dummylist);
      String text = "test";
      dummylistlist.get(j).add(text);
    }

    for (int j=0; j< 2; j++){
      System.out.println("arraylist "+j+" has size "+dummylistlist.get(j).size());
      System.out.println("Arraylist No."+j+" is ="+dummylistlist.get(j));
    }
}

And the output is:

arraylist 0 has size 2
Arraylist No.0 is =[test, test]
arraylist 1 has size 2
Arraylist No.1 is =[test, test]

But I expected it to be:

arraylist 0 has size 1
Arraylist No.0 is =[test]
arraylist 1 has size 1
Arraylist No.1 is =[test]

Why does the method add(text) appends the "test" String to all sublists so that it gets added once each loop? I don't understand. Can you help me to fix my code to achieve the latter output? Thank you in advance.

damned
  • 9
  • 3
  • Don't call `dummylistlist.add(dummylist);` You have only one list because of this, called `dummylist`. – Kajal Jun 04 '16 at 19:07
  • You're adding the same list twice into your "listlist" and because of this, adding "test" twice into `dummylist`. – Mick Mnemonic Jun 04 '16 at 19:07

2 Answers2

0

The problem is that you're creating only one list which you put into the other. Thus, when calling get(j), you're always retrieving the same inner list and adding the element to it. If you want distinct lists, create them inside the loop.

Christian Brüggemann
  • 2,152
  • 17
  • 23
0

If you want it to work, you need to initialize dummylist variable inside the for loop Since you have only one instance of dummylist inside your code, it is the same reference that you are adding at each loop iteration. That is why you need to create a new instance of ArrayList at each loop iteration

tfosra
  • 581
  • 5
  • 12