Set接口簡介
Set是不保存重複元素的Collection,Set接口只包含從Collection接口繼承的方法,並且增加禁止重複元素的限制。實現Set接口的通用類是HashSet,LinkedHashSet,TreeSet類。
- HashSet類。HashSet採用hashCode算法存放元素,元素的存放順序與插入順序無關。HashSet是爲了快速查找而實現的Set。由hashCode()和equals()方法保證唯一性。如果對象成員變量值相同即爲同一個對象的話,需要重寫hashCode()和equals()方法,通過ide可以自動生成。
- TreeSet類。TreeSet類採用紅黑樹數據結構(是一種自平衡的二叉樹,避免層級過深)對元素排序(默認自然排序),是保證元素字母排列順序的Set。它的查找速度比HashSet慢。根據比較的返回值是否是0來保證唯一性。有兩種方式進行排序,1、元素具備比較性,讓元素所屬的類實現Comparable接口。2、集合具備比較性,讓集合接收一個Comparator的實現類對象。
- LinkedHashSet類。LinkedHashSet是HashSet的子類,由哈希表和鏈表組成,哈希表保證元素的唯一性,鏈表保證取出與存儲的順序一致。
例子
- 獲取10個1至20的隨機數,要求隨機數不能重複
/**
* 獲取10個1至20的隨機數,要求隨機數不能重複。
* @author loveqRc
* */
public class RandomNum {
public static void main(String[] args) {
HashSet<Integer> hs=new HashSet<>();
Random rm=new Random();
while(hs.size()<10){
hs.add(rm.nextInt(20)+1);
}
for (Integer integer : hs) {
System.out.println(integer);
}
}
}
- 鍵盤錄入5個學生信息(姓名,語文成績,數學成績,英語成績),按照總分從高到低輸出到控制檯
/**
* 鍵盤錄入5個學生信息(姓名,語文成績,數學成績,英語成績),按照總分從高到低輸出到控制檯
*
* @author loveqRc
*
*/
public class StudentInfo {
public static void main(String[] args) {
System.out.println("請輸入學生信息");
TreeSet<Student> students=new TreeSet<>();
for (int i = 0; i < 5; i++) {
Student student=new Student();
System.out.println("請輸入第"+i+"個學生的名字");
Scanner scanner=new Scanner(System.in);
student.setName(scanner.nextLine());
System.out.println("請輸入學生的語文成績");
student.setChinese(Integer.valueOf(scanner.nextInt()));
System.out.println("請輸入學生的數學成績");
student.setMath(Integer.valueOf(scanner.nextInt()));
System.out.println("請輸入學生的英語成績");
student.setEnglish(Integer.valueOf(scanner.nextInt()));
students.add(student);
}
for (Student student : students) {
System.out.println(student.getName()+"的總分是:"+student.getTotal());
}
}
}
public class Student implements Comparable<Student> {
private Integer chinese;
private Integer english;
private Integer math;
private String name;
public Integer getChinese() {
return chinese;
}
public void setChinese(Integer chinese) {
this.chinese = chinese;
}
public Integer getEnglish() {
return english;
}
public void setEnglish(Integer english) {
this.english = english;
}
public Integer getMath() {
return math;
}
public void setMath(Integer math) {
this.math = math;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getTotal(){
return this.chinese+this.math+this.english;
}
@Override
public int compareTo(Student s) {
return -(this.getTotal()-s.getTotal());
}
}