简体   繁体   中英

object reference set in java

I need to create a Set of objects. The concern is I do not want to base the hashing or the equality on the objects' hashCode and equals implementation. Instead, I want the hash code and equality to be based only on each object's reference identity (ie: the value of the reference pointer).

I'm not sure how to do this in Java.

The reasoning behind this is my objects do not reliably implement equals or hashCode, and in this case reference identity is good enough.

I guess that java.util.IdentityHashMap is what you're looking for (note, there's no IdentityHashSet ). Lookup the API documentation:

This class implements the Map interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values). In other words, in an IdentityHashMap , two keys k1 and k2 are considered equal if and only if (k1==k2) . (In normal Map implementations (like HashMap ) two keys k1 and k2 are considered equal if and only if (k1==null ? k2==null : k1.equals(k2)) .)

This class is not a general-purpose Map implementation! While this class implements the Map interface, it intentionally violates Map 's general contract, which mandates the use of the equals method when comparing objects. This class is designed for use only in the rare cases wherein reference-equality semantics are required.

edit : See Joachim Sauer's comment below, it's really easy to make a Set based on a certain Map . You'd need to do something like this:

Set<E> mySet = Collections.newSetFromMap(new IdentityHashMap<E, Boolean>());

您可以将对象包装到包装器类中,然后可以实现hashcode并仅基于对象的标识进行equals

You can extend HashSet (or actually - AbstractSet ) , and back it with IdentityHashMap which uses System.identityHashCode(object) instead of obj.hashCode() .

You can simply google for IdentityHashSet , there are some implementations already. Or use Collections.newSetFromMap(..) as suggested by Joachim Sauer.

This of course should be done only if you are not in "possession" of your objects' classes. Otherwise just fix their hashCode()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM