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>() {