Java 集合-Set接口和三个子类实现
- Set
一个不包含重复元素的 collection。无序且唯一。
- HashSet
- LinkedHashSet
- TreeSet
HashSet是使用哈希表(hash table)实现的,其中的元素是无序的。HashSet的add、remove、contains方法 的时间复杂度为常量O(1)。
TreeSet使用树形结构(算法书中的红黑树red-black tree)实现的。TreeSet中的元素是可排序的,但add、remove和contains方法的时间复杂度为O(log(n))。TreeSet还提供了first()、last()、headSet()、tailSet()等方法来操作排序后的集合。
LinkedHashSet介于HashSet和TreeSet之间。它基于一个由链表实现的哈希表,保留了元素插入顺序。LinkedHashSet中基本方法的时间复杂度为O(1)。
~ HashSet
此类实现 Set 接口,由哈希表(实际上是一个 HashMap 实例)支持。它不保证 set 的迭代顺序;特别是它不保证该顺序恒久不变。此类允许使用 null 元素。
注意,此实现不是同步的。如果多个线程同时访问一个哈希 set,而其中至少一个线程修改了该 set,那么它必须 保持外部同步。
HashSet底层数据结构是哈希表(HashMap),哈希表依赖于哈希值存储,添加功能底层依赖两个方法:int hashCode(),boolean equals(Object obj)。
*构造方法
*常用方法
HashSet唯一性的解释,源码剖析:添加功能底层依赖两个方法:int hashCode(),boolean equals(Object obj)
1
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
//HashSet类 class HashSet implements Set{
private static final Object PRESENT = new Object();
private transient HashMap<E,Object> map;
// 构造方法,返回了一个HashMap
public HashSet() {
map = new HashMap<>();
}
//add方法
public boolean add(E e) {
return map.put(e, PRESENT)== null ;
}
} //HashMap类 class HashMap implements Map{
public V put(K key, V value) {
return putVal(hash(key), key, value, false , true );
}
final V putVal( int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0 )
n = (tab = resize()).length;
if ((p = tab[i = (n - 1 ) & hash]) == null )
tab[i] = newNode(hash, key, value, null );
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal( this , tab, hash, key, value);
else {
for ( int binCount = 0 ; ; ++binCount) {
if ((e = p.next) == null ) {
p.next = newNode(hash, key, value, null );
if (binCount >= TREEIFY_THRESHOLD - 1 ) // -1 for 1st
treeifyBin(tab, hash);
break ;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break ;
p = e;
}
}
if (e != null ) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null )
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null ;
}
} |
一个实例问题,在这种添加自定义对象的时候,两个类的属性值相等,但是依然会被判定为不同的元素,因为没有重写hashCode(),所以默认调用的是Object类的hashCode(),而不同类的hashCode一般是不同的。
1
2
3
4
5
6
7
8
9
10
11
|
HashSet<Student> hashSet = new HashSet<>();
Student s1 = new Student( "刘亦菲" , 22 );
Student s2 = new Student( "章子怡" , 25 );
Student s3 = new Student( "刘亦菲" , 22 );
hashSet.add(s1); hashSet.add(s2); hashSet.add(s3); System.out.println(hashSet); |
解决方法就是自己重写hashCode() 和 equals()方法,使用idea的alt+insert可以自动生成。
1
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
|
public class Student {
private String name;
private Integer age;
Student(String name, int age)
{
this .name=name;
this .age=age;
}
@Override
public int hashCode() {
// return 0;<br> return this.name.hashCode()+this.age*11;
}
@Override
public boolean equals(Object obj) {
if ( this == obj)
return true ;
if (!(obj instanceof Student))
return false ;
Student s = (Student) obj;
return this .name.equals(s.name) && this .age.equals(s.age);
}
} |
这里用到了instanceof操作符,这个操作符和== ,>=是同种性质的,只是是用英文描述的,是二元操作符,用来判断左边的是否为这个特定类或者是它的子类的一个实例。
~ LinkedHashSet
具有可预知迭代顺序的 Set 接口的哈希表和链接列表实现。此实现与 HashSet 的不同之外在于,后者维护着一个运行于所有条目的双重链接列表。此链接列表定义了迭代顺序,即按照将元素插入到 set 中的顺序(插入顺序)进行迭代。注意,插入顺序不 受在 set 中重新插入的 元素的影响。
哈希表保证元素的唯一性,链表保证元素有序,也就是存入顺序和取出顺序相同。
~ TreeSet
基于 TreeMap
的 NavigableSet
实现。使用元素的自然顺序对元素进行排序,或者根据创建 set 时提供的 Comparator
进行排序,具体取决于使用的构造方法。
注意,此实现不是同步的。如果多个线程同时访问一个 TreeSet,而其中至少一个线程修改了该 set,那么它必须 外部同步。
有两种排序方式:A-自然排序,也是默认排序(实现Comparable),B-比较器排序。取决于构造方法。
*构造方法
*常用方法
1
2
3
4
5
6
7
8
9
|
// 会自动排序 TreeSet<Integer> treeSet = new TreeSet<>();
treeSet.add( 12 );
treeSet.add( 13 );
treeSet.add( 2 );
treeSet.add( 4 );
for ( int i:treeSet) System.out.println(i);
|
TreeSet的唯一性解释,源码剖析:唯一性根据比较的返回值是否为0,如果为零,则相等;排序的方式有两种,自然排序和比较器排序。
1
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
//TreeSet类 class TreeSet implements Set{
private static final Object PRESENT = new Object();
private transient NavigableMap<E,Object> m;
TreeSet(NavigableMap<E,Object> m) {
this .m = m;
}
public TreeSet() {
this ( new TreeMap<>());
}
public boolean add(E e) {
return m.put(e, PRESENT)== null ;
}
} //TreeMap类 class TreeMap implements Map{
<br> //红黑树实现
public V put(K key, V value) {
Entry<K,V> t = root;<br> //建立根节点
if (t == null ) {
compare(key, key); // type (and possibly null) check
root = new Entry<>(key, value, null );
size = 1 ;
modCount++;
return null ;
}
int cmp;
Entry<K,V> parent;
// split comparator and comparable paths
Comparator<? super K> cpr = comparator;
if (cpr != null ) {
do {
parent = t;
cmp = cpr.compare(key, t.key);
if (cmp < 0 )
t = t.left;
else if (cmp > 0 )
t = t.right;
else
return t.setValue(value);
} while (t != null );
}
else {
if (key == null )
throw new NullPointerException();
@SuppressWarnings ( "unchecked" )
Comparable<? super K> k = (Comparable<? super K>) key;
do {
parent = t;
cmp = k.compareTo(t.key);
if (cmp < 0 )
t = t.left;
else if (cmp > 0 )
t = t.right;
else
return t.setValue(value);
} while (t != null );
}
Entry<K,V> e = new Entry<>(key, value, parent);
if (cmp < 0 )
parent.left = e;
else
parent.right = e;
fixAfterInsertion(e);
size++;
modCount++;
return null ;
}
} |
对象中的实例,自然排序:具体类实现Comparable接口,重写Comparable方法。构造方法为默认构造
1
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
52
|
public class Student implements Comparable<Student>{
private String name;
private Integer age;
Student(String name, int age)
{
this .name=name;
this .age=age;
}
// @Override // public int hashCode() { // return 0; // } // // @Override // public boolean equals(Object obj) { // if(this == obj) // return true; // // if(!(obj instanceof Student)) // return false; // // Student s = (Student) obj; // return this.name.equals(s.name) && this.age.equals(s.age); // } @Override
public boolean equals(Object o) {
if ( this == o) return true ;
if (o == null || getClass() != o.getClass()) return false ;
Student student = (Student) o;
if (name != null ? !name.equals(student.name) : student.name != null ) return false ;
return age != null ? age.equals(student.age) : student.age == null ;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0 ;
result = 31 * result + (age != null ? age.hashCode() : 0 );
return result;
}
@Override
// 从小到大
public int compareTo(Student o) {
int num = this .age-o.age;
return num== 0 ? this .name.compareTo(o.name):num;
}
} |
对象中的实例,比较器排序:自定义比较器,实现Comparator接口。构造方法为带比较器的构造
1
2
3
4
5
6
7
8
|
class MyComparator implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
int num = o1.age-o2.age;
return num== 0 ?o1.name.compareTo(o2.name):num;
}
} |
当然也可以使用匿名内部类来实现。
1
2
3
|
TreeSet<Student> treeset = new Treeset<>( new Comparator<Student>(){
public int compare(Student o1, Student o2) { int num = o1.age-o2.age; return num== 0 ?o1.name.compareTo(o2.name):num; }
}) |