The clone() method

  • Thread starter Andrew Mallinson
  • Start date
A

Andrew Mallinson

Hi

Just wondering if someone could explain - the workings of the clone method
to me. Im aware that it creates a copy of the object. But say you have a
vector of Integers - and you clone the vector does the new vector have
different Integer objects (although of the same value) in it - or references
to the first vectors objects.

Now say you have a vector of your own objects(classes that youve created) -
that dont support the clone method. And you clone the vector - does java
create a new copy of each of the objects in the vector and put them into the
new vector or again are they just references.

Thanks very much inadvance for your help
Regards
Andy
 
C

Christophe Vanfleteren

Andrew said:
Hi

Just wondering if someone could explain - the workings of the clone method
to me. Im aware that it creates a copy of the object. But say you have a
vector of Integers - and you clone the vector does the new vector have
different Integer objects (although of the same value) in it - or
references to the first vectors objects.

It only create a shallow copy, so all the references in the Vector will be
the same.
Now say you have a vector of your own objects(classes that youve created)
- that dont support the clone method. And you clone the vector - does java
create a new copy of each of the objects in the vector and put them into
the new vector or again are they just references.

How would it know how to copy the objects? And it doesn't behave like that
even when they would implement cloneable, so once again, they're just again
references to the original objects.

You should also read the following to get some extra insight on the problems
with clone() in Java:
http://www.artima.com/intv/bloch13.html
 
R

Ryan Stewart

Christophe Vanfleteren said:
It only create a shallow copy, so all the references in the Vector will be
the same.


How would it know how to copy the objects? And it doesn't behave like that
even when they would implement cloneable, so once again, they're just again
references to the original objects.

You should also read the following to get some extra insight on the problems
with clone() in Java:
http://www.artima.com/intv/bloch13.html

Or you could just go to
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html

and read the details of the method and exactly what it does and decide how
to deal with it.
 

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
473,995
Messages
2,570,225
Members
46,815
Latest member
treekmostly22

Latest Threads

Top