Map怎么使用自定义引用类型做主键

问题演示

import java.util.HashMap;
import java.util.Map;

class Student{
    private String name = "张三";
    private String tel = "123";
}
public class TestJson {

    public static void main(String[] args) {
         Student st1 = new Student();
         Student st2 = new Student();
         Map<Student, String> map = new HashMap<Student, String>();
         map.put(st1, null);
         map.put(st2, null);
         System.out.println(map.size());

    }

}

如上代码,st1,st2属性完全一样,分别使用st1,st2作为主键存入map,发现map结果等于2,为什么不是1呢?

map的存储结构有点像一个树,有很多节点,每个节点又是一个链表;
我们put一条数据时,先调用主键对象的hashcode方法找到对应的节点,
然后遍历这个节点对应的链表,使用equals方法比较是否存在和自己相同的主键;

我们调用 st1.hashcode == st2.hashcode发现是false,当然默认的equals方法取得是对象地址,肯定也是不相等,这个时候hashcode不相等,就找到不同的节点,equals方法不相等,就找不出相同的主键;
因此如果Map要是用自定义引用类型做主键,需要重写hashcode、equals方法;

class Student{
    private String name = "张三";
    private String tel = "123";

    public int hashCode() {
         int result = 17;  
            result = result * 31 + name.hashCode();  
            result = result * 31 + tel.hashCode();  

            return result;
    }

    public boolean equals(Object  obj) {
        Student st = (Student)obj;
        if(null != st) {
            return StringUtils.equals(st.name, st.name) && StringUtils.equals(st.tel, st.tel);
        }
        return false;
    }
}
public class TestJson {

    public static void main(String[] args) {
         Student st1 = new Student();
         Student st2 = new Student();
         Map<Student, String> map = new HashMap<Student, String>();
         map.put(st1, null);
         map.put(st2, null);
         System.out.println(map.size());

    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值