clone(): ArrayList.clone() I thought does a shallow copy

Shallow copy does not mean that they point to the same memory location. That would be just an assignment:List b = a;.

Cloning creates a new instance, holding the same elements. This means you have 2 different lists, but their contents are the same. If you change the state of an object inside the first list, it will change in the second list. (Since you are using an immutable type – Integer – you can’t observe this)

However, you should consider not using clone(). It works fine with collections, but generally it’s considered broken. Use the copy-constructors – new ArrayList(originalList)

Leave a Comment