1
|——SortedSet接口——TreeSet实现类
2
Set接口——|——HashSet实现类
3
|——LinkedHashSet实现类
4
HashSet
5
此类实现 Set 接口,由哈希表(实际上是一个 HashMap 实例)支持。它不保证集合的迭代顺序;特别是它不保证该顺序恒久不变。此类允许使用 null 元素。
6
此类为基本操作提供了稳定性能,这些基本操作包括 add、remove、contains 和 size,假定哈希函数将这些元素正确地分布在桶中。对此集合进行迭代所需的时间与 HashSet 实例的大小(元素的数量)和底层 HashMap 实例(桶的数量)的“容量”的和成比例。因此,如果迭代性能很重要,则不要将初始容量设置得太高(或将加载因子设置得太低)。
7
8
我们应该为要存放到散列表的各个对象定义hashCode()和equals();
9
import java.util.HashSet;
10
import java.util.Iterator;
11
public class HashSetTest
{
12
public static void main(String[] args)
13
{
14
HashSet hs=new HashSet();
15
/**//*hs.add("one");
16
hs.add("two");
17
hs.add("three");
18
hs.add("four");*/
19
hs.add(new Student(1,"zhangsan"));
20
hs.add(new Student(2,"lishi"));
21
hs.add(new Student(3,"wangwu"));
22
hs.add(new Student(1,"zhangsan"));
23
24
Iterator it=hs.iterator();
25
while(it.hasNext())
26
{
27
System.out.println(it.next());
28
}
29
}
30
}
31
class Student //HashSet要重写hashCode和equals方法
32

{
33
int num;
34
String name;
35
Student(int num,String name)
36
{
37
this.num=num;
38
this.name=name;
39
}
40
public String toString()
41
{
42
return "num :"+num+" name:"+name;
43
}
44
public int hashCode()
45
{
46
return num*name.hashCode();
47
}
48
public boolean equals(Object o)
49
{
50
Student s=(Student)o;
51
return num==s.num && name.equals(s.name);

2

3

4

5

6

7

8

9

10

11



12

13



14

15


16

17

18

19

20

21

22

23

24

25

26



27

28

29

30

31

32



33

34

35

36



37

38

39

40

41



42

43

44

45



46

47

48

49



50

51
