开发者

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:

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

Questions

  1. Am I right?

  2. Shallow copy or deep copy?

  3. If it is shallow copy, how can I ma开发者_如何学编程ke the deep copy possible?

    objArray[3] = newObj; 
    
  4. 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. 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.


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.


  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;


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜