5YrsLaterDBA
5YrsLaterDBA

Reputation: 34730

Array assignment operation question

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:

Questions

  1. Am I right?

  2. Shallow copy or deep copy?

  3. If it is shallow copy, how can I make the deep copy possible?

    objArray[3] = newObj; 
    
  4. Does this rule applies to other Java container types, such as Queue, List, ...?

Upvotes: 1

Views: 1804

Answers (5)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298818

copy all the contents of the newObj to the space referred by objArray[3].

Nope, it will store a reference to [the Object referenced by: thanks Jon Skeet] newObj at objArray[3]. The original object is not changed or copied in any way, just the reference to it.

Upvotes: 1

Michael Borgwardt
Michael Borgwardt

Reputation: 346240

Answer 1&2: No. Only a reference to the object is copied. newObj and objArray[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 be Serializable

Answer 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.

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1499840

Well, it will copy "all the contents of the newObj" into objArray[3]... but the contents (or value) of the newObj variable is just a reference to the object. In other words, consider:

objArray[3] = newObj;
newObj.setFoo("hello");

System.out.println(objArray[3].getFoo()); // prints "hello"

(assuming a simple property, of course).

Basically, the value of a variable (including array elements) is never an object. It's always a reference or a primitive value. It's always passed or copied by value.

Upvotes: 5

Jacob
Jacob

Reputation: 43209

  1. No, it does not copy the content. It just creates another reference.
  2. Shallow. (See 1)
  3. You cannot use that statement if you want a deep copy. You have to override the clone-method of java.lang.Object in your Class MyClass and use that or create copy constructor.
  4. It applies to all data types that are not primitives like int or double;

Upvotes: 2

cadrian
cadrian

Reputation: 7376

no copy at all. The reference to the object is set in the array.

Upvotes: 1

Related Questions