• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How to make independent copies of the lists

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.



 
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Read up on deep copy vs shallow copy, it explains what you are seeing.
 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
     
    Consider Paul's rocket mass heater.
    reply
      Bookmark Topic Watch Topic
    • New Topic