1

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
  • 1
    why not check and see for your self ?
    – yurib
    Feb 25, 2013 at 21:26

1 Answer 1

7

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.

2
  • The reason I'm asking is that I have a big Graph object where nodes are of type Graph too. And when I traverse the graph, I need to put some of the nodes into an array Graph[] and I was wondering if this is expensive and that's why worried about hidden copying of objects into array positions. So does it mean that my array will be created as fast as similar array of pointers in C++? Feb 25, 2013 at 21:38
  • @SophieSperner: Yes, very similar to that.
    – Jon Skeet
    Feb 25, 2013 at 21:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.