Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ArrayList of ArrayList

Tags:

java

arraylist

The following code outputs

[[100, 200, 300], [100, 200, 300]].  

However, what I expect is

[[100, 200, 300], [100, 200]],  

Where am I wrong?

public static void main(String[] args) {     ArrayList<ArrayList<Integer>> outer = new ArrayList<ArrayList<Integer>>();     ArrayList<Integer> inner = new ArrayList<Integer>();              inner.add(100);          inner.add(200);      outer.add(inner);     outer.add(inner);      outer.get(0).add(300);      System.out.println(outer);  } 
like image 911
Jie Avatar asked Aug 05 '14 20:08

Jie


People also ask

Can I have an ArrayList of ArrayLists?

ArrayList of user defined objects Since ArrayList supports generics, you can create an ArrayList of any type. It can be of simple types like Integer , String , Double or complex types like an ArrayList of ArrayLists, or an ArrayList of HashMaps or an ArrayList of any user defined objects.

Can you add ArrayList to ArrayList in Java?

Approach: ArrayLists can be joined in Java with the help of Collection. addAll() method. This method is called by the destination ArrayList and the other ArrayList is passed as the parameter to this method. This method appends the second ArrayList to the end of the first ArrayList.

Why ArrayList is used in ArrayList?

The ArrayList in Java can have the duplicate elements also. It implements the List interface so we can use all the methods of the List interface here. The ArrayList maintains the insertion order internally. It inherits the AbstractList class and implements List interface.


1 Answers

You are adding a reference to the same inner ArrayList twice to the outer list. Therefore, when you are changing the inner list (by adding 300), you see it in "both" inner lists (when actually there's just one inner list for which two references are stored in the outer list).

To get your desired result, you should create a new inner list :

public static void main(String[] args) {     ArrayList<ArrayList<Integer>> outer = new ArrayList<ArrayList<Integer>>();     ArrayList<Integer> inner = new ArrayList<Integer>();              inner.add(100);          inner.add(200);     outer.add(inner); // add first list     inner = new ArrayList<Integer>(inner); // create a new inner list that has the same content as                                              // the original inner list     outer.add(inner); // add second list      outer.get(0).add(300); // changes only the first inner list      System.out.println(outer); } 
like image 111
Eran Avatar answered Sep 21 '22 03:09

Eran