Set集合
Set子接口
特点:无序、无下标、元素不可重复
Set子接口的使用
/**
* 特点:无序 不可重复
*/
public class Demo1 {
public static void main(String[] args) {
//创建集合
Set<String> set = new HashSet<String>();
//添加数据
set.add("苹果");
set.add("西瓜");
set.add("梨子");
System.out.println(set.toString());
//删除
// set.remove("苹果");
// System.out.println(set.toString());
//遍历[重点]
//增强for
for (String s : set) {
System.out.println(s);
}
//迭代器
Iterator<String> it = set.iterator();
while (it.hasNext()){
System.out.println(it.next());
}
//判断
set.contains("苹果");
set.isEmpty();
}
}
Set实现类
-
HashSet [重点]
-
基于HashCode实现元素不重复
-
存储结构:哈希表(数组+链表+红黑树)
-
当存入元素的哈希码相同时,会调用equals进行确认,如果结果为true,则拒绝后者存入。
-
-
TreeSet
-
基于排列顺序实现元素不重复
-
实现了SortedSet接口,对集合元素自动排序
-
元素对象的类型必须实现Comparable接口,指导排序规则
-
通过ComparaTo方法确定是否为重复元素
-
HashSet使用
添加元素、删除数据、遍历操作、判断操作可以和Set子接口的方类似
存储过程:
-
根据hashcode计算保存的位置,如果此位置为空,则直接保存,如果不为空则执行第二步
-
使用equals方法、如果equals方法为true,则认为是重复,否则、形成链表
TreeSet使用
存储结构:红黑树(二叉查找树)
添加元素、删除数据、遍历操作、判断操作可以和Set子接口的方类似
//要求:元素必须要实现Comparable接口
//compareTo()方法返回值为0,认为是重复元素
public class Demo1 {
public static void main(String[] args) {
TreeSet<Student> students = new TreeSet<>();
Student s1 = new Student("张三", 20);
Student s2 = new Student("李四", 20);
Student s3 = new Student("王五", 20);
students.add(s1);
students.add(s2);
students.add(s3);
System.out.println("元素个数:"+students.size());
System.out.println(students.toString());
}
}
附:Student类
public class Student implements Comparable<Student>{
private String name;
private int age;
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;
}
Comparator接口
Comparator:实现定制比较(比较器)
实现之后,可以不实现Comparable接口
public class Demo1 {
public static void main(String[] args) {
//创建集合,并指定比较规则
TreeSet<Student> students = new TreeSet<>(new Comparator<Student>() {