如何保证HashMap自定义类key 值的唯一性

来源:互联网 发布:网络监控方案有几种 编辑:程序博客网 时间:2024/05/16 08:18

1.LinkedHashMap: 由哈希表保证key的唯一性,由链表保证key的有序
(这个有序是指存储和取出时的顺序一致,而不是进行排序 )

2.TreeMap可以保证key的唯一性和key的排序。

3.Map 集合中,所有的Key都是唯一的。

4.假定有Student s1 = new Student(“张三”,27); Student s4 = new Student(“张三”,27); 如果不重写hashCode()和equals方法就存储到HashMap<Student,String>中就会发现:s1和s4同时在一个集合里。但是我们真实情况是希望s1和s4是同一个人,不要都被存储到集合中。做法是:

在Student类中重写hashCode()和equals方法

@Override    public int hashCode() {        final int prime = 31;        int result = 1;        result = prime * result + age;        result = prime * result + ((name == null) ? 0 : name.hashCode());        return result;    }    @Override    public boolean equals(Object obj) {        if (this == obj)            return true;        if (obj == null)            return false;        if (getClass() != obj.getClass())            return false;        Student other = (Student) obj;        if (age != other.age)            return false;        if (name == null) {            if (other.name != null)                return false;        } else if (!name.equals(other.name))            return false;        return true;    }
0 0
原创粉丝点击