• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to make independent copies of the lists  RSS feed

 
Ganapathy Asha
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I am trying to create an independent copy of the ArrayList, please let me know how to create:
I have tried with the following, but the original list is getting modified when i change the copied one.



 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Read up on deep copy vs shallow copy, it explains what you are seeing.
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am never convinced that cloning is the best way to do things. If you find a copy of Effective Java™ by Joshua Bloch, you find that he doesn't rate the clone() method very highly. If you really have to take copies of your objects, consider a copy constructor. Then you can writeThere are about four ways you can return a List:-
  • 1: Return the List itself. Find the chapter in Bloch's book about defensive copies first. You can change anything in the List and each change is visible in each copy.
  • 2: Return a copy of the List: return new ArrayList<>(oldList); You now have two completely independent Lists.
  • 3: Return a read‑only copy: return Arrays.unmodifiableList(myList); Any changes in the original will be visible in the copy but the copy cannot be changed independently.
  • 4: Combine No 2 and No 3: return Arrays.unmodifiableList(new ArrayList<>(oldList)); Now the copy is both read‑only and impossible to change. Even changing the original will not change the copy.
  • Unfortunately none of the above will prevent you having problems about the elements changing their state. Find out about immutable objects which are also thread‑safe.
     
    It is sorta covered in the JavaRanch Style Guide.
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!