If I have a piece of code like this:
MyClass[] objArray = new MyClass[7];
//assign values to objArray
//do something here
//sometime later
MyClass newObj = new MyClass();
objArray[3] = newObj;
The last statement above will do the following:
- copy all the contents of the
newObjto the space referred to by objArray[3].
Questions
-
Am I right?
-
Shallow copy or deep copy?
-
If it is shallow copy, how can I make the deep copy possible?
objArray[3] = newObj; -
Does this rule applies to other Java container types, such as Queue, List, …?
Answer 1&2: No. Only a reference to the object is copied.
newObjandobjArray[3]will afterwards refer to the same object instance.Answer 3: If you want a copy, you have to implement it yourself. You could implement a copy constructor or
Clonable, or for a simple deep copy, serialize and deserialize the object, but that requires it and all objects it consists of to beSerializableAnswer 4: It’s exactly the same for all Java Objects: the reside on the heap, and the code works only with references to the objects. Container types usually implement a copy constructor that does a shallow copy. There is no deep copy functionality that is automatically available for all classes.