• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ArrayList and shallow cloning

 
RaviNada Kiran
Ranch Hand
Posts: 528
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have made a ArrayList al , with 3 Objects in it .

second i made an ArrayList by cloning the first one that is al.

when i make any changes onto the second ArrayList (Obtained from the clone) .

The changes are not reflecting , why so (As i read that the clone() will produce only a shallow copy)
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please explain more. If you clone a List you will get two Lists which initially have the same contents; adding to list no 1 will not add to list no 2, surely? That is how I read the API documentation.
 
amitabh mehra
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See if this old thread here can help you understand it better.
 
higherzl Harez
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
RaviNada Kiran wrote:I have made a ArrayList al , with 3 Objects in it .

second i made an ArrayList by cloning the first one that is al.

when i make any changes onto the second ArrayList (Obtained from the clone) .

The changes are not reflecting , why so (As i read that the clone() will produce only a shallow copy)


if and only if the Objects you added into is String

if not , the changes you made to the second ArrayList's elements, the first ArrayList changed too.
 
Rob Spoor
Sheriff
Pie
Posts: 20512
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
higherzl Harez wrote:if and only if the Objects you added into is String

you must mean immutable. Integer, Long and any other immutable objects behave the same as String - once created they can never change.

if not , the changes you made to the second ArrayList's elements, the first ArrayList changed too.

Technically the ArrayList itself does not change, but its contents change. You are most definitely right about that.
An example:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic