I sometimes assume that if oldObject != newObject
then the object has changed - which seems a fair assumption in most cases but is it truly a bad assumption?
In short, under what situation could the following code print "Same!"?
static WeakReference<Object> oldO = null;
...
Object o = new Object();
oldO = new WeakReference(o);
// Do some stuff with o - could take hours or even days to complete.
...
// Discard o (or let it go out of scope).
o = null;
// More stuff - could be hours or days later.
...
o = new Object();
// Later still.
if ( o == oldO.get() ) {
System.out.println("Same!");
}
I realise that this is indeed remotely possible because an object reference is essentially the memory address of the object (or could be in some JVM). But how likely is it? Are we talking decades of run-time before it actually happens?
Added
My apologies - please assume that oldO
is some form of weak
reference that does not stop it from being collected. Perhaps it is Weak
as the code (now) suggests or the reference is store in a database or a file somewhere.
Yes, two or more references, say from parameters and/or local variables and/or instance variables and/or static variables can all reference the same object.
Object references can be assigned between object reference variables. This means that the references in multiple reference variables can point to the same object (sharing).
The == operator can be used to check if two object references point to the same object. To be able to compare two java objects of the same class the boolean equals(Object obj) method must be overridden and implemented by the class. The implementer decides which values must be equal to consider two objects to be equal.
Can a certain object have different addresses? It means that the reference (pointer) value can be stored in many places. We call each copy of the pointer a reference. So there are many references.
(I'm answering what I think what you really wanted to know, rather than the particular snippet you have)
It's implementation dependant. The contract of object reference is that as long as the object is still alive, no other object will compare == with it. This implies that after the object is garbage collected, the VM is free to reuse the same object reference.
Implementation of Java may choose to use an increasing integer for object reference, in which case you can only get the same object reference when the reference counter overflows back to 0. Other implementation may use memory location, which makes it more likely for the same reference to be reused. In any case, you should define your own object identity if that matters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With