Set接口和常用方法
Set接口基本介绍
- 无序 添加和取出的顺序不一致 没有索引
- 不允许重复元素 所以最多包含一个null
- Set接口实现类 常用 HashSet TreeSet
Set接口的常用方法
和List接口一样 Set接口也是Collection的子接口 常用方法和Collection接口一样
Set接口的遍历方式
同Collcetion遍历方式一样
- 可以使用迭代器
- 增强for
- 不能使用索引方式来获取
HashSet练习
- 定义一个Employee类 包含name age
- 创建三个对象放入HashSet中
- 当name和age相同时 认为是相同员工 不能添加
idea重写hashCode 调用add时 进行hash值判断 名字年龄相同 则返回相同hash
HashSet hashSet = new HashSet();
hashSet.add(new Employee("张三", 18)) ;
hashSet.add(new Employee("李四", 20)) ;
hashSet.add(new Employee("张三", 18)) ;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return age == employee.age && Objects.equals(name, employee.name);
}
@Override
public int hashCode() {
//idea重写hashCode 调用add时 进行hash值判断 名字年龄相同 则返回相同hash
return Objects.hash(name, age);
}
LinkedHashSet说明
- LinkedHashSet是HashSet的子类
- LinkedHashSet底层是一个LinkedHashMap 底层维护了一个 数组+双向链表
- LinkedHashSet根据元素的hashCode值来决定元素的存储位置 同时使用链表维护元素的次序 这使得元素看起来是插入顺序保存的
- LinkedHashSet不允许添加重复元素