Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

clone( )

 
Abder-Rahman Ali
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If we had the following for example:

ArrayList<String> list = new ArrayList<String>();
...
...
...

ArrayList<Inbound> copy = (ArrayList<Inbound>)list.clone();

I know that it is a copy of the object.

But, my main point here is, what do we mean by "copy"? What do we actually copy?

Thanks.

[ May 28, 2008: Message edited by: Abder-Rahman Ali ]
[ May 28, 2008: Message edited by: Abder-Rahman Ali ]
 
Justin Fox
Ranch Hand
Posts: 802
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Looks to me that yes you do copy, the object and it's
contents/attributes.

Justin Fox
 
Stevi Deter
Ranch Hand
Posts: 265
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you check the API for ArrayList.clone(), you'll learn it's a shallow copy. A new ArrayList object is returned, but it contains the same elements (not new copies) of the original ArrayList.

To see how this works, try this little program:



The output is:

list and copy are same object? false
item 0 is same object? true
item 0 is equals? true
item 1 is same object? true
item 1 is equals? true
item 2 is same object? true
item 2 is equals? true
// here we do String s = list.get(0); s = new String("different");
item 0 is same object? true
item 0 is equals? true
// here we did list.set(0, new String("new"));
item 0 is same object? false
item 0 is equals? false
[ May 28, 2008: Message edited by: Stevi Deter ]
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also see the links in this recent thread.
 
Abder-Rahman Ali
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much for your nice replies.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic