一 基本概念
* set接口的实现类 * 无序 没有索引 不能重复(唯一) * 提供了增删查的操作 * 底层数据结构是哈希表 > hashCode不同 散列出来的位置可能一样 可能不一样 > hashCode相同 散列出来的位置一定一样 * 自定义对象的存储要注意equals和hashCode方法的重写
Student类
public class Student {
// 声明字段
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@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 &&
Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
HashSet的基本使用
/**
* set接口的实现类
* 无序 没有索引 不能重复(唯一)
* 提供了增删查的操作
* 底层数据结构是哈希表
*/
public class HashSetSDemo {
public static void main(String[] args) {
// 声明一个hashset集合
Set<String> set = new HashSet<>();
// 进行增删查的操作
// 增 add
set.add("古天乐");
set.add("福尔摩斯");
set.add("东野圭吾");
System.out.println(set);
boolean flag = set.add("古天乐");
System.out.println(flag); // false 因为不能重复元素
// 删 remove
set.remove("福尔摩斯");
System.out.println(set);
System.out.println("-----------------");
// 遍历
Iterator<String> it = set.iterator();
// 通过迭代器对象的hasNext()和next去获取元素
while (it.hasNext()){
String item = it.next();
System.out.println(item);
}
// 语法糖
for (String s : set) {
System.out.println(s);
}
System.out.println("==================");
// 查
int size = set.size();
boolean result = set.contains("古天乐"); // 这个实际中用的多
System.out.println("元素个数:" + size);
System.out.println("是否包含:" + result);
}
}
HashSet的自定义对象使用
/**
* 自定义对象的存储
* hashCode不同 散列出来的位置可能一样 可能不一样
* hashCode相同 散列出来的位置一定一样
*/
public class HashSetSDemo2 {
public static void main(String[] args) {
// 创建三个自定义的Student对象
Student stu1 = new Student("古天乐",18);
Student stu2 = new Student("彭于晏",19);
Student stu3 = new Student("东野圭吾",29);
HashSet<Student> set = new HashSet<>();
set.add(stu1);
set.add(stu2);
set.add(stu3);
System.out.println(set);
// 遍历
Iterator<Student> it = set.iterator();
while(it.hasNext()){
Student ele = it.next();
System.out.println(ele);
}
// 如果创建一个同一个古天乐 但是从内存上 地址不一致 但在业务上 是认为是同一个人
// 打印出来的结果 会存进set集合里面
// 要进行equals的比较 不然就会存在同一个集合里
// 原来的equals不满足业务需求 需要重写(覆盖)equals和hashCode方法
Student stu4 = new Student("古天乐",18);
set.add(stu4);
System.out.println(set); // [Student{name='古天乐', age=18}, Student{name='古天乐', age=18}, Student{name='东野圭吾', age=29}, Student{name='彭于晏', age=19}]
}
}