-2

Now, I have encountered this problem:

I have a non-empty array list declared as original. Then I do this :

ArrayList<ArrayList<Integer>> temp = (ArrayList<ArrayList<Integer>>) original.clone();

temp.get(0).set(1,-1) ;

but the result was that unexpectedly the element at index 1 in both lists were changed.

How can I fix this problem ?

azurefrog
  • 10,785
  • 7
  • 42
  • 56
  • Before remove: `original=[[1, 2, 3], [4, 5, 6]] temp=[[1, 2, 3], [4, 5, 6]]`, after remove: `original=[[1, 2, 3], [4, 5, 6]] temp=[[1, 2, 3]]` – azurefrog Apr 29 '16 at 20:06
  • 1
    I tried your code as well and it works like a charm. unless you're trying to remove an element from the inner array! – Arijoon Apr 29 '16 at 20:06
  • how ? actually i am doing this but it's the same like removing : temp.get(0).set(1, -1); – abdo yasser Apr 29 '16 at 20:10
  • Have you tried using the `addAll(Collection)` method? – Rabbit Guy Apr 29 '16 at 20:14
  • It's really not the same at all. `temp.remove(1)` is changing `temp`, `temp.get(0).set(1, -1)` is changing a number in a list contained by `temp`. – azurefrog Apr 29 '16 at 20:14
  • Ok it's my mistake – abdo yasser Apr 29 '16 at 20:15
  • You need to make a [deep copy](http://stackoverflow.com/questions/715650/how-to-clone-arraylist-and-also-clone-its-contents) of `original`. – azurefrog Apr 29 '16 at 20:16
  • I applaud your attempt to simplify the code for your question. Just make sure in the future that you actually run your sample code to make sure you didn't simplify your error out of it! ;-) – azurefrog Apr 29 '16 at 20:18

3 Answers3

1

clone makes a shallow copy of the ArrayList. Either make it's Deep Copy since the ArrayList is object type so it can also make new object of it's reference.

1

You have to deep copy, you can try below code for(int element:original) { temp.add(element); }

user2044822
  • 135
  • 6
0

clone makes a shallow copy of the ArrayList. In a sense, this means affecting the ArrayList from one reference also affects the other reference.

Instead, use new ArrayList(original).

Edit: My mistake. You'd have to go through the contents of your ArrayList and clone each object inside. Unfortunately for you, you have ArrayLists inside your ArrayList, so you'd have to do a lot of iterating if you want distinct Integers.

Zircon
  • 4,677
  • 15
  • 32