Set容器特點:
① Set容器是一個不包含重復元素的Collection,並且最多包含一個null元素,它和List容器相反,Set容器不能保證其元素的順序;
② 最常用的兩個Set接口的實現類是HashSet和TreeSet;
HashSet及常用API
① HashSet擴展AbstractSet並且實現Set接口;
② HashSet使用散列表(又稱哈希表)進行存儲;
③ 構造方法:
a) HashSet()
b) HashSet(Collection c)
c) HashSet(int capacity)
d) HashSet(int capacity,float fillRatio)
④ HashSet沒有定義任何超過它的父類和接口提供的其它方法;
⑤ 散列集合沒有確保其元素的順序,因為散列處理通常不參與排序;
1 HashSet<String> data=new HashSet<String>();
2 data.add("張三");
3 data.add("李四");
4 data.add("jay");
5 data.add("jack");
6 data.add("jay");
7 System.out.println(data);
輸出結果:
[李四, 張三, jay, jack]
此處第二個jay沒有存入;
可以將其打印出來System.out.println(data.add("jay"));,結果顯示第一個為true,第二個為false
編寫一個Student類:
1 class Student{
2 private String name;
3 private int age;
4 public Student(String name, int age) {
5 super();
6 this.name = name;
7 this.age = age;
8 }
9 public String getName() {
10 return name;
11 }
12 public void setName(String name) {
13 this.name = name;
14 }
15 public int getAge() {
16 return age;
17 }
18 public void setAge(int age) {
19 this.age = age;
20 }
21 }
主方法中添加及輸出
1 HashSet<Student> stuSet=new HashSet<Student>();
2 System.out.println(stuSet.add(new Student("張三",20)));
3 System.out.println(stuSet.add(new Student("李四",30)));
4 System.out.println(stuSet.add(new Student("張三",20)));
5 System.out.println(stuSet.size());
6
輸出結果: