Array of object references

折月煮酒 提交于 2019-12-24 15:34:40

问题


In Java, let a custom object o is of type CustomObject. Then CustomObject o2 = o; would make a reference without copying the contents of o to o2. But will this behaviour remain for an array of CustomObjects:

CustomObject[] os = new CustomObject[2];
os[1] = o;
os[2] = o;

Will os[1] and os[2] be references or they will be direct copies of o and thus separate objects?


回答1:


Well, you actually mean os[0] and os[1] as arrays are 0-based in Java... but yes, they'll be references. Both array elements will refer to the same object.

Importantly, o isn't an object either:

  • o is a variable: it has a name and a value
  • The value of o is a reference: it's either null, or it refers to an object
  • An object has fields, is of a certain execution-time type, etc

The value of an expression (whether it's a simple variable value, the result of a method call or whatever) is never an object in Java - it's always either a reference or a primitive value.

The way the Java Language Specification defines arrays is just as a collection of variables:

An array object contains a number of variables. The number of variables may be zero, in which case the array is said to be empty. The variables contained in an array have no names; instead they are referenced by array access expressions that use non-negative integer index values. These variables are called the components of the array. If an array has n components, we say n is the length of the array; the components of the array are referenced using integer indices from 0 to n - 1, inclusive.

So it's really a bit like doing:

// Creating the pseudo-array
CustomObject o0 = null;
CustomObject o1 = null;

// Populating it
o0 = o;
o1 = o;

As ever, the assignment operator just copies the value of the right hand side to the left hand side. That value is a reference.



来源:https://stackoverflow.com/questions/15076763/array-of-object-references

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!