Set集合
一个不包含重复元素的 collection。更确切地讲,set 不包含满足 e1.equals(e2) 的元素对 e1 和 e2,并且最多包含一个 null 元素。
关于Set集合不进行详细的说明,其子类实现其方法,我们直接看其子类。(想了解更多的可以查看API)
HashSet集合
- HashSet存储字符串并遍历
//存储字符
HashSet<String> set = new HashSet<>();
boolean a = set.add("a");//添加成功返回true,失败false
boolean b = set.add("a");
boolean c = set.add("c");
boolean d = set.add("d");
System.out.println(a);//结果:true
System.out.println(b);//结果:false
System.out.println(set);//结果:abc
//遍历
for(String s : set){
System.out.println(s)
}
HashSet 存储自定义对象保证元素的唯一性
在存储自定义对象的时候HasSet的hashCode()和equals()方法默认比较的是当前引用(地址值),所以要重写hashCode()和equals()方法
//Student类中有姓名和年龄两个属性,以及构造方法,下面只显示重写hashCode()和equlas()方法
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age &&
name.equals(student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
//main方法
public static void main(String[] args) {
HashSet<Student> set = new HashSet<>();
//添加对象
set.add(new Student("张三",20));
set.add(new Student("张三",20));
set.add(new Student("李四",21));
set.add(new Student("李四",21));
set.add(new Student("王五",22));
set.add(new Student("王五",22));
//遍历
for (Student s : set){
System.out.println(s.getName()+","+s.getAge());
/*结果是:
张三,20
王五,22
李四,21
*/
}
}
- 1.HashSet原理
- 我们使用Set集合都是需要去掉重复元素的, 如果在存储的时候逐个equals()比较, 效率较低,哈希算法提高了去重复的效率, 降低了使用equals()方法的次数
- 当HashSet调用add()方法存储对象的时候, 先调用对象的hashCode()方法得到一个哈希值, 然后在集合中查找是否有哈希值相同的对象
- 如果没有哈希值相同的对象就直接存入集合
- 如果有哈希值相同的对象, 就和哈希值相同的对象逐个进行equals()比较,比较结果为false就存入, true则不存
- 2.将自定义类的对象存入HashSet去重复
- 类中必须重写hashCode()和equals()方法
- hashCode(): 属性相同的对象返回值必须相同, 属性不同的返回值尽量不同(提高效率)
- equals(): 属性相同返回true, 属性不同返回false,返回false的时候存储