Can I compare WeakReference variables in java?

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

Despite the fact that weak settings are cleared of the hash map, I also want to be able to manually remove "MyObject" from the HashMap. This is the central listener object.

When I add elements to an arraylist that is associated with the main value of the hashmap key, I use .add(new WeakReference<MyObject>(owner))

When I want to remove the "I" from an external location, I send the "owner" as a parameter, which is the real object. So how can I remove this object manually from my hashmap? Can I request a new WeakReference generated from an inbound owner parameter? Will the old "new WeakReference<MyObject>(owner)"and the new "new WeakReference<MyObject>(owner)"be equal? Therefore, I can remove it from hashmap.

+5
source share
3 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 the method is equalsnot overridden in the Weak Link document. Therefore, it by default checks whether both links are equal and which are not.

Sentence:

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

you can change listto mapand use the identifier in the object as for a weak job. And when the owner calls, use the identifier of this object to remove the weak link.

+6
source

, WeakReference, Reference equals(). , equals() Object, , .

+4

The obvious option is to loop through the list and compare the target object with the referent of each Reference ( owner.equals(reference.get())or owner == reference.get(), if you check that both variables point to the same object).

+2
source

All Articles