java中如何使用"自定义类"作为HashMap中的key呢?
下文笔者讲述在HashMap中使用自定义类作为HashMap的key的方法分享,如下所示
实现思路:
我们只需重写类的
hashCode()和equals()方法
重写HashCode的功能
重写hashCode():
由于需要计算存储数据的存储位置,
而且使用hashCode()用于确定数据的存储位置
编写好的hashCode()可减少hash碰撞
重写equals的功能
由于需遵守自反性、对称性、传递性、一致性以及 对任何非null的引用值x x.equals(null)必须返回false的这几个特性 其目的是为了保证key在哈希表中的唯一性
String类源码
/**
* Compares this string to the specified object. The result is {@code
* true} if and only if the argument is not {@code null} and is a {@code
* String} object that represents the same sequence of characters as this
* object.
*
* <p>For finer-grained String comparison, refer to
* {@link java.text.Collator}.
*
* @param anObject
* The object to compare this {@code String} against
*
* @return {@code true} if the given object represents a {@code String}
* equivalent to this string, {@code false} otherwise
*
* @see #compareTo(String)
* @see #equalsIgnoreCase(String)
*/
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
return (anObject instanceof String aString)
&& (!COMPACT_STRINGS || this.coder == aString.coder)
&& StringLatin1.equals(value, aString.value);
}
public int hashCode() {
int h = hash;
if (h == 0 && !hashIsZero) {
h = isLatin1() ? StringLatin1.hashCode(value)
: StringUTF16.hashCode(value);
if (h == 0) {
hashIsZero = true;
} else {
hash = h;
}
}
return h;
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


