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); }
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.
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.
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.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With