Is an element in an array a reference to an object or a reference it self?
Solution 1
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.
Solution 2
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.
Solution 3
- Assume that arrayOfObjects starts at memory location 100.
- Assume that validIndex is 0.
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);
- Assume that the call to new allocated the object a memory location 300.
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.
Comments
-
Samuel about 2 years
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 originaloldObject
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?
-
Samuel about 13 yearsSorry the naming terminate is in context with my project it could basicly be any method call, but so the method call is called on the new instance? Do i get that right?
-
duffymo about 13 yearsNo, if terminate is not static it's invoked on the instance - in your example's case, oldObject. Not the new instance that you made the array reference to point to.