美文网首页
Java 在 Map 中使用复杂数据类型作为 Key

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

作者: 字母数字或汉字 | 来源:发表于2016-10-02 15:00 被阅读1043次

    有时候你想这么做:

    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() 的五条原则

    1. 自反性。
      x.equals(x) 为 true
    2. 对称性。
      x.equals(y) 为 true,那么 y.equals(x) 为 true
    3. 传递性。
      x.equals(y) 为 true 且 y.equals(z) 为 true,那么 x.equals(z) 也为 true
    4. 一致性。
      对于 x.equals(y),只要判定信息不变,无论比较多少次结果均应相同。
    5. x != null 为 true,那么 x.equals(null) 为 false

    相关文章

      网友评论

          本文标题:Java 在 Map 中使用复杂数据类型作为 Key

          本文链接:https://www.haomeiwen.com/subject/vdsdyttx.html