• 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
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

Cloning Doubt

 
Ranch Hand
Posts: 298
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
As per the API for the ArrayList's clone method, it says that:


According to what i have understood from the statement is that:
The ArrayList's elements inside the List are not copied, they point to the same reference. That is, if i change an element in the original arrayList, this change can as well be viewed in the Cloned List.
Am i right?

This program explains what Cloning in ArrayList does:

The output shows:


I have gone through the ArrayList code and they have used System.arrayCopy() method to copy the elements of the original ArrayList to the Cloned ArrayList. So the behavior, but why such behavior?
Doesnt this falsify the meaning of shallow cloning?
 
Ranch Hand
Posts: 1258
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
System.arrayCopy does a shallow copy also, so no it doesn't falsify the meaning of shallow cloning. For one thing, collections can't really make any assumptions about the types of objects that they hold. They may or may not be able to be clonable, so promising that an ArrayList will return a deep-copy would be stupid, since it may be impossible!
 
Run away! Run away! Here, take this tiny ad with you:
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic