您的位置:首页 > 编程语言 > Java开发

Java 在 Map 中使用复杂数据类型作为 Key

2016-10-16 00:00 183 查看
有时候你想这么做:

Map<User, Profile> map = new HashMap<>();
// 添加一些数据
map.put(new User(1), getProfile(1));
// 取用这些数据
if (map.containsKey(new User(1)) {
doSomething();
}

但默认情况下这是不能成功的,因为在 HashMap 的实现中,是这么处理的:

// 代码有精简,改变了对 null 值的判断逻辑,不过这不是重点
if (key != null
&& e.hash == key.hashCode()
&& (e.key == key || key.equals(e.key)) {
return e;
}

注意,hashCode 相同,不一定 equals() 返回 true。

也就是说,我们要手动实现
equals()
hashCode()
才能达到我们的目的。

class User {

private Integer id;

@Override
public int hashCode() {
return this.id != null ? this.id : 0;
}

@Override
public boolean equals(Object obj) {
return obj instanceof User && (this.id.equals(((User) obj).id));
}
}

大功告成。

Think in Java 中设计
equals()
的五条原则

自反性。
x.equals(x)
为 true

对称性。
x.equals(y)
为 true,那么
y.equals(x)
为 true

传递性。
x.equals(y)
为 true 且
y.equals(z)
为 true,那么
x.equals(z)
也为 true

一致性。
对于
x.equals(y)
,只要判定信息不变,无论比较多少次结果均应相同。

x != null
为 true,那么
x.equals(null)
为 false
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: