java的HashMap的key为对象,有什么注意点

如果HashMap的key为一个学生,value值为一个学生的成绩,我们希望通过学生对象查询到学生的成绩

public class Main {
    public static void main(String[] args){
        Student student1=new Student("1","tom",20);
        Student student2=new Student("1","tom",20);
        Map<Student,Integer> map=new HashMap<>();
        map.put(student1,100);
        System.out.println(student1.hashCode()+"::"+student2);
        System.out.println(map.get(student1)+"::"+map.get(student2));
    }
}
class Student {
    private String type;
    private String name;
    private  int age;
    Student(String type,String name,int age){
        this.age=age;
        this.type=type;
        this.name=name;
    }
 
}

输出:

com.example.demo.Student@deb6432::com.example.demo.Student@28ba21f3
100::null

虽然我们的student1和student2是都是tom但是却无法成功通过student2获取到student1,因为创建了两次对象,对象地址不一致,而HashMap就是通过对象的=hashCode()和equals判定是否为同一个key,这就需要我们重写这两个方法

这里提供一种金典的hash算法

public class Main {
    public static void main(String[] args){
        Student student1=new Student("1","tom",20);
        Student student2=new Student("1","tom",20);
        Map<Student,Integer> map=new HashMap<>();
        map.put(student1,100);
        System.out.println(student1+"::"+student2);
        System.out.println(map.get(student1)+"::"+map.get(student2));
    }
}
class Student {
    private String type;
    private String name;
    private  int age;
    Student(String type,String name,int age){
        this.age=age;
        this.type=type;
        this.name=name;
    }
    @Override
    public int hashCode() {
        int B=31; // 31 131 1313 13131 131313 etc..
        int hash=0;
        hash=hash*B+age;
        hash=hash*B+type.toUpperCase().hashCode();
        hash=hash*B+name.toUpperCase().hashCode();
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if(this==obj){
            return true;
        }
        if(obj==null){
            return false;
        }
        Student student=(Student) obj;
        return student.type.toUpperCase().equals(this.type.toUpperCase())&&
                student.age==this.age&&student.name.toUpperCase().equals(this.name.toUpperCase());
    }
}

输出:

com.example.demo.Student@19635::com.example.demo.Student@19635
100::100

如果对hashCode有更高的要求,可以使用MD5,sha之类的算法

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值