Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i compare WeakReference variables in java?

I have a HashMap<MyClass,ArrayList<WeakReference<MyObject>>> variable.

Eventhough weakrefences are cleaned from the hashmap, i also want to be able to manually remove "MyObject" from HashMap. This is a central listener object.

When i add items to the arraylist that is linked to the main hashmap key's value, i use .add(new WeakReference<MyObject>(owner))

When i want to remove "self" from an external place, i send "owner" as the parameter which is the real object. So how can i remove this object manually from my hashmap? Can i query with a new WeakReference generated from the incoming owner parameter? Will the old "new WeakReference<MyObject>(owner)" and the new "new WeakReference<MyObject>(owner)" be equal? So i could remove it from the hashmap.

like image 913
frankish Avatar asked Mar 01 '13 09:03

frankish


2 Answers

Will the old "new WeakReference(owner)" and the new "new WeakReference(owner)" be equal?

No they will not be equal. both are different objects and equals method is not overridden in Weak Reference. So it by default checks whether both the references are equal and they are not.

Suggestion:

Map<MyClass,Map<String,WeakReference<MyObject>>>

you can change the list to a map and use some ID kind of thing in object as the key for weak reference. And when the owner calls, use the ID of that object to remove the weak reference.

like image 165
Narendra Pathai Avatar answered Sep 30 '22 21:09

Narendra Pathai


No, because neither WeakReference nor its parent Reference class overrides the equals() method. So it inherits the equals() method from Object, which only considers two objects to be equal if they are the same object.

like image 24
JB Nizet Avatar answered Sep 30 '22 21:09

JB Nizet