is an object deep-copied when added to a collection?

L

lucia.roibal

Say, I do the follow,

Date d=new Date();

ArrayList<Data> alist= new ArrrayList();

alist.add(d);

//modify d

will the element d in the alist also modified?
 
M

Mark Space

Say, I do the follow,

Date d=new Date();

ArrayList<Data> alist= new ArrrayList();

alist.add(d);

//modify d

will the element d in the alist also modified?

Java almost never does a deep copy, any time. Even .clone() does not
deep-copy, it does a shallow copy.

When you add d to alist, you add d, the reference, nothing else. Java
always uses semantics which are equivalent to pointers in C++.

Vector<Date*> alist = Vector<Date*>();

Date *d = new Date();

alist.add(d);

Or something like that, it's been a long time since C++.....
 
A

Andrea Francia

Mark said:
Vector<Date*> alist = Vector<Date*>();

Date *d = new Date();

alist.add(d);

Or something like that, it's been a long time since C++.....

Your example is almost correct.
The only things that need to be corrected are the initialisation
and the name of the method which add an entry to the vector.

vector<Date *> alist; // default constructor called implicitly

Date *d = new Date;

alist.push_back(d);

Also I don't use c++ since long time ago, maybe I mistaked something else.
 
P

Paul Tomblin

In a previous article said:
"yes", that's not the answer to the question in the subject. Objects
_aren't_ "deep copied" when added to a collection. They aren't even
"shallow copied". Only the reference to the object is copied to the
collection. The object isn't copied at all, deep or otherwise.

The great thing about that is that the cost of adding an object to a
collection or map is pretty minuscule (probably only 4 or 8 bytes). So if
you might need to access the same object in two different orders, it's not
a big deal to make two TreeSets with different Comparators, rather than
re-sorting the same collection every time you need it in a different
order, or having multiple Maps with different keys.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,434
Messages
2,571,691
Members
48,796
Latest member
Greg L.

Latest Threads

Top