Reputation: 18586
If i have an array of AnObjects and i do this:
AnObject oldObject = arrayOfObjects[validIndex];
arrayOfObjects[validIndex] = new AnObject(oldObject.getVariableForContruction);
oldObject.terminate();
Does the new content of arrayOfObjects[validIndex]
get terminated, or does the original oldObject
get terminated?
In other words: Does oldObject contain a reference to an AnObject or does it contain a reference to a reference to an AnObject?
Upvotes: 1
Views: 15118
Reputation: 61526
Then arrayOfObjects[validIndex] means memory location 100.
Assume that memory location 100 has a value of 200.
AnObject oldObject = arrayOfObjects[validIndex];
oldObject is at memory location 200.
arrayOfObjects[validIndex] = new AnObject(oldObject.getVariableForContruction);
Then the memory location 100 has a value of 300.
oldObject.terminate();
oldObject never changed, so it is still pointing at memory location 200.
So, the item that used to be in the array is terminated after it is replaced with the new object.
Upvotes: 1
Reputation: 30723
In Java there are no references to references. Ignoring primitive types, then all variables/array cells hold references to objects. Here's a snippet that illustrates this:
class Something {
public int n;
}
Something[] arr = new Something[2];
Something s = new Something();
s.n = 2;
arr[0] = s;
System.out.print(arr[0].n); // Output: "2"
arr[0].n += 1;
System.out.print(s.n); // Output: "3"
Upvotes: 0
Reputation: 7139
It contains a reference to an object. In this case the oldObject would get terminated - not the new instance you have placed in the array.
Upvotes: 1
Reputation: 308753
This code is a bit confusing. Your array of objects must have a reference to AnObject
.
AnObject oldObject = arrayOfObjects[validIndex];
You assign that reference to oldObject
here.
arrayOfObjects[validIndex] = new AnObject(oldObject.getVariableForContruction);
Now you set the array reference at validIndex
to point to a new instance of AnObject
. It no longer points to oldObject
.
oldObject.terminate();
It's a reference to an object on the heap.
oldObject
refers to an instance on the heap; the reference in the array points to the new instance that you created on the heap.
If oldObject
is terminated (whatever that means), it's immaterial to the new instance you created. The array still points to the new instance.
Upvotes: 3