前言
集合就是一組數的集合,就像是一個容器,但是我們應該清楚的是集合中存放的都是對象的引用,而不是真正的實體。而我們常說的集合中的對象其實指的就是對象的引用。
我們可以把集合理解為一個小型數據庫,用于存放數據,我們對集合的操作也就是數據的增刪改查,在 java 中有兩個頂層接口 collection 和 map 用于定義和規范集合的相關操作。這篇文章主要說一下集合框架中的 collection 部分。
collection 表示一組對象,這些對象可以是有序也可以是無序的,它提供了不同的子接口滿足我們的需求。我們主要看看 list 和 set 。
list 整體的特征就是有序可重復。我們需要研究的是上圖中具體的實現類都有什么特性。底層的實現原理是什么,首先來看一看 list 的古老的實現類 vector ,說是古老是因為在 jdk 1.0 的時候就出現了,都走開,我要開始看源碼了!這些源碼來自于 jdk 1.7。
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
|
public class vector<e> extends abstractlist<e> implements list<e>, randomaccess, cloneable, java.io.serializable { /** * the array buffer into which the components of the vector are * stored. */ protected object[] elementdata; /** * the number of valid components in this {@code vector} object. */ protected int elementcount; /** * the amount by which the capacity of the vector is automatically * incremented when its size becomes greater than its capacity. if * the capacity increment is less than or equal to zero, the capacity * of the vector is doubled each time it needs to grow. */ protected int capacityincrement; public vector() { this ( 10 ); } // 添加元素 public synchronized boolean add(e e) { modcount++; ensurecapacityhelper(elementcount + 1 ); elementdata[elementcount++] = e; return true ; } // 刪除元素 public synchronized e remove( int index) { modcount++; if (index >= elementcount) throw new arrayindexoutofboundsexception(index); e oldvalue = elementdata(index); int nummoved = elementcount - index - 1 ; if (nummoved > 0 ) system.arraycopy(elementdata, index+ 1 , elementdata, index, nummoved); elementdata[--elementcount] = null ; // let gc do its work return oldvalue; } // 修改元素 public synchronized e set( int index, e element) { if (index >= elementcount) throw new arrayindexoutofboundsexception(index); e oldvalue = elementdata(index); elementdata[index] = element; return oldvalue; } // 查找元素 public synchronized e get( int index) { if (index >= elementcount) throw new arrayindexoutofboundsexception(index); return elementdata(index); } ... |
就以上源碼分析就可以知道關于 vector 的特征。1 底層實現是使用數組來存儲數據,所以相應的查找元素和添加元素速度較快,刪除和插入元素較慢。2 數組的初始長度為 10 ,當長度不夠時,增長量也為 10 使用變量 capacityincrement 來表示。3 方法的聲明中都加入了 synchronized 關鍵字,線程安全的,所以效率相應降低了。 4 沒分析出來的再看一遍。
下面開始看 arraylist 的源碼。
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
|
public class arraylist<e> extends abstractlist<e> implements list<e>, randomaccess, cloneable, java.io.serializable { private static final long serialversionuid = 8683452581122892189l; /** * default initial capacity. */ private static final int default_capacity = 10 ; /** * shared empty array instance used for empty instances. */ private static final object[] empty_elementdata = {}; /** * the array buffer into which the elements of the arraylist are stored. * default_capacity when the first element is added. */ private transient object[] elementdata; /** * constructs an empty list with an initial capacity of ten. */ public arraylist() { super (); this .elementdata = empty_elementdata; } // 添加元素 public boolean add(e e) { ensurecapacityinternal(size + 1 ); // increments modcount!! elementdata[size++] = e; return true ; } // 增加數組的長度 private void grow( int mincapacity) { // overflow-conscious code int oldcapacity = elementdata.length; int newcapacity = oldcapacity + (oldcapacity >> 1 ); if (newcapacity - mincapacity < 0 ) newcapacity = mincapacity; if (newcapacity - max_array_size > 0 ) newcapacity = hugecapacity(mincapacity); // mincapacity is usually close to size, so this is a win: elementdata = arrays.copyof(elementdata, newcapacity); } ... |
因為源碼和 vector 類似,所以有些就不貼了,但是不耽誤我們繼續分析 arraylist 。1 底層存儲數據使用的還是數組,長度依舊為 10 ,但是進步了,沒有在剛開始創建的時候就初始化,而是在添加第一個元素的時候才初始化的。2 方法的聲明少了 synchronized 關鍵字,線程不安全,但性能提高了。3 數組長度不夠時,會自動增加為原長度的 1.5 倍。
以上分析也能體現出 vector 和 arraylist 的差別。主要就是想說 vector 已經不用了。使用 arraylist 即可,關于線程安全問題,后面再說。
接著看 linkedlist 的實現,上源碼 ~
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
75
76
77
78
79
80
|
public class linkedlist<e> extends abstractsequentiallist<e> implements list<e>, deque<e>, cloneable, java.io.serializable { transient int size = 0 ; /** * pointer to first node. */ transient node<e> first; /** * pointer to last node. */ transient node<e> last; /** * constructs an empty list. */ public linkedlist() { } // 每一個元素即為一個節點,節點的結構如下(這是一個內部類啊) private static class node<e> { e item; node<e> next; node<e> prev; node(node<e> prev, e element, node<e> next) { this .item = element; this .next = next; this .prev = prev; } } // 添加元素 public boolean add(e e) { linklast(e); return true ; } void linklast(e e) { final node<e> l = last; final node<e> newnode = new node<>(l, e, null ); last = newnode; if (l == null ) first = newnode; else l.next = newnode; size++; modcount++; } // 刪除某個節點的邏輯 e unlink(node<e> x) { // assert x != null; final e element = x.item; final node<e> next = x.next; final node<e> prev = x.prev; if (prev == null ) { first = next; } else { prev.next = next; x.prev = null ; } if (next == null ) { last = prev; } else { next.prev = prev; x.next = null ; } x.item = null ; size--; modcount++; return element; } ... |
重點就是 linkedlist 的底層實現是雙鏈表。這樣就會有以下特性,1 查找元素較慢,但是添加和刪除較快。2 占內存,因為每一個節點都要維護兩個索引。3 線程不安全 。4 對集合長度沒有限制。
以上,list 的幾個實現已經分析完成,以后再談到 vector ,arraylist ,linkedlist 之間的區別應該不會不知所云了吧!還要接著看 collection 的另一個子接口 set 。首先有個大前提,set 中存儲的元素是無序不可重復的。然后我們再來看實現類是如何實現的。下面開始 hashset 的表演。
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 hashset<e> extends abstractset<e> implements set<e>, cloneable, java.io.serializable { private transient hashmap<e,object> map; // dummy value to associate with an object in the backing map private static final object present = new object(); /** * constructs a new, empty set; the backing <tt>hashmap</tt> instance has * default initial capacity (16) and load factor (0.75). */ public hashset() { map = new hashmap<>(); } // 添加元素,其實就是像 map 中添加主鍵,所以添加的元素不能重復 public boolean add(e e) { return map.put(e, present)== null ; } // 實現 iterable 接口中的 iterator 方法。 public iterator<e> iterator() { return map.keyset().iterator(); } ... |
看了源碼才發現,1 原來 hashset 就是對 hashmap 的封裝啊,底層實現是基于 hash 表的,回頭有必要再好好的介紹一下 hash 相關的知識。2 set 集合中的值,都會以 key 的形式存放在 map 中,所以說 set 中的元素不能重復。3 線程不安全。4 允許存放空值,因為 map 的鍵允許為空。
今天要說的最后一個實現類終于出現啦,他就是 treeset ,這個實現類中的元素是有序的!注意這里說的有序是指按照一定的規則排序,而我們說 set 集合中的元素無序是因為添加進集合的順序和輸出的順序不保證一致。treeset 是怎么保證有序我們待會再說,還是一樣的套路,是對 treemap 的封裝,線程依舊不安全。
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
|
public class treeset<e> extends abstractset<e> implements navigableset<e>, cloneable, java.io.serializable { /** * the backing map. */ private transient navigablemap<e,object> m; // dummy value to associate with an object in the backing map private static final object present = new object(); /** * constructs a set backed by the specified navigable map. */ treeset(navigablemap<e,object> m) { this .m = m; } /** * constructs a new, empty tree set, sorted according to the * natural ordering of its elements. all elements inserted into * the set must implement the comparable interface. */ public treeset() { this ( new treemap<e,object>()); } /** * constructs a new, empty tree set, sorted according to the specified * comparator. all elements inserted into the set must be mutually * comparable by the specified comparator * if the comparable natural ordering of the elements will be used. */ public treeset(comparator<? super e> comparator) { this ( new treemap<>(comparator)); } // 添加元素方法 public boolean add(e e) { return m.put(e, present)== null ; } ... |
我們可以看到 treeset 中構造函數上方的注釋,treeset 要保證元素有序,保證有序的思路是在添加元素的時候進行比較。
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
|
... // 這是 treemap 的 put 方法的節選,為了看到比較的過程。 public v put(k key, v value) { ... // 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(); 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 ); } ... } |
java 中提供了兩種方式,第一種方法,需要我們所添加對象的類實現 comparable 接口,進而實現 compareto 方法,這種方式也叫自然排序,我們并沒有傳入什么排序規則。這種方式對應 treeset 的空參構造器。而另一種方式就是定制排序,即我們自己定義兩個元素的排序規則,在實例化 treeset 的時候傳入對應的排序規則即可,對應于 treeset 中帶有 comparator 接口的構造器,這里面需要實現 compare 方法 。有點迷糊了是吧,舉個例子看看 ~
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
75
|
public class person implements comparable<person>{ public string name; public integer age; public person(string name,integer age) { this .name = name; this .age = age; } /* 自定義的比較的邏輯: * 首先按照對象的 name 屬性排序 * 其次按照 age 屬性排序 * 方法的返回值為 0 ,大于 0,小于 0 ,分別對應于 相等,大于,和小于 */ @override public int compareto(person o) { int i = this.name.compareto(o.name); if(i == 0){ return this.age.compareto(o.age); }else { return i; } } @override public string tostring() { return "[person] name:"+this.name+" age:"+this.age; } } // 以下是測試代碼 public static void main(string[] args) { treeset<person> set = new treeset<>(); set.add(new person("ajk923",20)); set.add(new person("bjk923",20)); set.add(new person("ajk923",21)); set.add(new person("bjk923",21)); for (person person : set) { system.out.println(person.tostring()); } /* [person] name:ajk923 age:20 [person] name:ajk923 age:21 [person] name:bjk923 age:20 [person] name:bjk923 age:21 */ ----以下為定制排序的部分----匿名內部類實現 comparator 接口---- treeset<person> set2 = new treeset<>(new comparator<person>() { @override public int compare(person o1, person o2) { int i = o1.age.compareto(o2.age); if(i == 0){ return o1.name.compareto(o2.name); }else { return i; } } }); set2.add(new person("ajk923",20)); set2.add(new person("bjk923",20)); set2.add(new person("ajk923",21)); set2.add(new person("bjk923",21)); for (person person : set2) { system.out.println(person.tostring()); } /* [person] name:ajk923 age:20 [person] name:bjk923 age:20 [person] name:ajk923 age:21 [person] name:bjk923 age:21 */ } |
上面就是自然排序和定制排序的應用。要說明幾點:
1 定制排序和自然排序同時存在的話,優先執行定制排序。可以看看上面的 put 方法的實現 。
2 自然排序對應 comparable 接口,定制排序對應 comparator 接口。
3 string ,包裝類,日期類都已經實現了 comparable 接口的 comparato 方法,所以我上面的例子中都偷懶了,沒有自己實現具體比較,而是直接調用現成的。
看到這里,也算是對 collection 有了整體的認識,但是這里我并沒有說到具體的 api ,我現在日常也用不到幾個方法,就放一張 collection 接口的結構圖吧,方法也比較簡單,看個名字就大概知道什么意思了。
還是要重點說一下 iterator 方法。這個方法定義在 iterable 接口中(collection 繼承了 iterable 接口),方法返回的是 iterator 接口對象。iterator 中定義了迭代器的操作規則,而 collection 的實現類中是具體的實現。iterator 接口中定義了 next ,hasnext 和 remove 方法。看一下在arraylist 中是如何實現的吧。
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
|
private class itr implements iterator<e> { int cursor; // index of next element to return int lastret = - 1 ; // index of last element returned; -1 if no such int expectedmodcount = modcount; public boolean hasnext() { return cursor != size; } @suppresswarnings ( "unchecked" ) public e next() { checkforcomodification(); int i = cursor; if (i >= size) throw new nosuchelementexception(); object[] elementdata = arraylist. this .elementdata; if (i >= elementdata.length) throw new concurrentmodificationexception(); cursor = i + 1 ; return (e) elementdata[lastret = i]; } public void remove() { if (lastret < 0 ) throw new illegalstateexception(); checkforcomodification(); try { arraylist. this .remove(lastret); cursor = lastret; lastret = - 1 ; expectedmodcount = modcount; } catch (indexoutofboundsexception ex) { throw new concurrentmodificationexception(); } } final void checkforcomodification() { if (modcount != expectedmodcount) throw new concurrentmodificationexception(); } } |
應用起來還是比較簡單的,使用一個 while 循環即可。看下面這個例子。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public static void main(string[] args) { list<integer> list = new arraylist<>(); list.add( 1 ); list.add( 2 ); list.add( 3 ); iterator<integer> it = list.iterator(); while (it.hasnext()) { integer i = it.next(); system.out.println(i); } } |
不知道你有沒有發現,除了 vector 以外,保存集合元素的那個變量都定義為 transient 不管你是數組,node 或是 map ,不由得我又要想一想為什么這樣設計?
先看一下 transient 的作用吧!java 的 serialization 提供了一種持久化對象實例的機制。當持久化對象時,可能有一個特殊的對象數據成員,我們不想用 serialization 機制來保存它。為了在一個特定對象的一個域上關閉 serialization,可以在這個域前加上關鍵字 transient 。當一個對象被序列化的時候,transient 型變量的值不包括在序列化的表示中,非 transient 型的變量是被包括進去的。
那么為什么要這么做呢,好好的標準序列化不用,原因如下:
對于 arraylist 來說,底層實現是數組,而數組的長度和容量不一定相等,可能容量為 10 ,而我們的元素只有 5 。此時序列化的時候就有點浪費資源,序列化和反序列化還是要的,故 arraylist 自己實現了兩個方法,分別是 writeobject 和 readobject ,用于序列化和反序列化。
對于 hashset 和 hashmap 來說,底層實現都是依賴于 hash 表,而不同的 jvm 可能算出的 hashcode 值不一致,這樣在跨平臺的時候就會導致序列化紊亂。故也重寫了那兩個方法。借用一句似懂非懂的話:
當一個對象的物理表示方法與它的邏輯數據內容有實質性差別時,使用默認序列化形式有 n 種缺陷,所以應該盡可能的根據實際情況重寫序列化方法。
對應于 collection ,有一個 collections 工具類,其中提供很多方法,比如說集合的排序,求子集合,最大值,最小值,交換,填充,打亂集合等等,還記得上面說到的實現類中存在線程不安全的情況吧,這個工具類中提供很多對應的 synchronized 的方法。
后記 :不知不覺中擴展了這么多知識點,實話說,肯定還有遺漏的地方,就我現在能想到的依然還有很多,除去 hash 表和 hash 算法這一部分之外,我還沒有對底層的數據結構進一步分析,數組,鏈表,二叉樹等等,現在是分析不動了,本文已經很長了。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。
原文鏈接:https://www.cnblogs.com/YJK923/p/9498975.html