简体   繁体   English

使用引用相等的集合

[英]Collection using reference equality

在 Java 中是否可以创建使用引用相等(即== )而不是equals()方法的HashMap

Use the IdentityHashMap class.使用IdentityHashMap类。 This is a variant of HashMap in which == and System.identityHashCode() are used instead of Object.equals(Object) and Object.hashCode() .这是HashMap的变体,其中使用==System.identityHashCode()代替Object.equals(Object)Object.hashCode()

Note that this class intentionally violates the API contract of java.util.Map which requires that key equality is based on equals(Object) .请注意,此类故意违反了java.util.Map的 API 契约,该契约要求键相等性基于equals(Object)

You can override the equals method of the objects you insert into the HashMap to test reference equality.您可以覆盖插入到 HashMap 中的对象的 equals 方法来测试引用相等性。

As in:如:

public boolean equals(Object obj) {
    return this == obj;
}

The IdentityHashmap class comes with standard Java. IdentityHashmap类随标准 Java 一起提供。 From the JavaDoc:来自 JavaDoc:

This class implements the Map interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values).此类使用哈希表实现 Map 接口,在比较键(和值)时使用引用相等代替对象相等。 In other words, in an IdentityHashMap, two keys k1 and k2 are considered equal if and only if (k1==k2).换句话说,在 IdentityHashMap 中,两个键 k1 和 k2 被认为是相等的,当且仅当 (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)).) (在普通 Map 实现(如 HashMap)中,当且仅当 (k1==null ? k2==null : k1.equals(k2)) 时,两个键 k1 和 k2 被认为是相等的。)

Be aware that many functions that take Map s do so assuming that they will use equals , rather than reference equality.请注意,许多采用Map的函数都假设它们将使用equals而不是引用相等。 So be careful which functions you pass your IdentityHashmap to.所以要小心你将IdentityHashmap传递给哪些函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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