前言
今天學(xué)學(xué)java中如何創(chuàng)建一個(gè)空集合以及空集合的一些使用場景和相關(guān)的坑。開始之前,我們先來看一下java判斷集合是否為空
list.isempty() list.size()==0 list==null的區(qū)別:
1. isempty()方法是用來判斷集合中有沒有元素
2. size()方法是判斷集合中的元素個(gè)數(shù)
3. isempty()和size()==0意思一樣,沒有區(qū)別,通用。
4. if(list ==null)是判斷有沒有這個(gè)集合
在我們判斷集合是否為空的時(shí)候這樣寫就萬無一失:
1
2
3
4
5
6
7
|
list<string> list = new arraylist<>(); if (list!= null &&!list.isempty()){ //走集合不為空的邏輯 } |
下面開始本文的正文,你可能會(huì)問,這好像沒有什么好講的,空集合不就是new一個(gè)嘛,也就是像new arraylist<string>()這樣創(chuàng)建一個(gè)不久行了嗎?其實(shí)這也是一種創(chuàng)建空集合的方法,但今天小編講下通過另外一種方式創(chuàng)建空集合,以及兩種方式之間的差異。
一、通過collections.emptylist()創(chuàng)建空集合
java集合工具類中提供了一系列創(chuàng)建集合的靜態(tài)方法,其中包括創(chuàng)建線程同步相關(guān)的collections.synchronizedxxx()方法、空集合相關(guān)的collections.emptyxxx()方法。通過這種方式創(chuàng)建的空集合,既然是空的,就不允許你往集合中添加元素和刪除元素,也就是不能調(diào)用相應(yīng)add()和remove()方法,我先來看看collections類創(chuàng)建空集合的部分源代碼:
1
2
3
4
5
6
7
|
public static final list empty_list = new emptylist<>(); ...... public static final <t> list<t> emptylist() { return (list<t>) empty_list; } |
你會(huì)發(fā)現(xiàn)上面的emptylist()方法默認(rèn)返回的是前面的靜態(tài)變量empty_list,你可能會(huì)說,既然empty_list是static的,那我直接通過collections.empty_list獲取不就好了,沒錯(cuò),這樣做也可以,只不過在某些需要泛型的場景下,調(diào)用emptylist()方法提供了相應(yīng)的泛型支持。
那為什么這種方式不能添加和移除元素呢?我們來看看emptylist內(nèi)部類是怎么定義的:
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
|
// 繼承自abstractlist抽象類 private static class emptylist<e> extends abstractlist<e> implements randomaccess, serializable { private static final long serialversionuid = 8842843931221139166l; public iterator<e> iterator() { return emptyiterator(); } public listiterator<e> listiterator() { return emptylistiterator(); } public int size() { return 0 ;} public boolean isempty() { return true ;} public boolean contains(object obj) { return false ;} public boolean containsall(collection<?> c) { return c.isempty(); } public object[] toarray() { return new object[ 0 ]; } public <t> t[] toarray(t[] a) { if (a.length > 0 ) a[ 0 ] = null ; return a; } public e get( int index) { throw new indexoutofboundsexception( "index: " +index); } public boolean equals(object o) { return (o instanceof list) && ((list<?>)o).isempty(); } public int hashcode() { return 1 ; } @override public boolean removeif(predicate<? super e> filter) { objects.requirenonnull(filter); return false ; } @override public void replaceall(unaryoperator<e> operator) { objects.requirenonnull(operator); } @override public void sort(comparator<? super e> c) {} // override default methods in collection @override public void foreach(consumer<? super e> action) { objects.requirenonnull(action); } @override public spliterator<e> spliterator() { return spliterators.emptyspliterator(); } // preserves singleton property private object readresolve() { return empty_list; } } |
從上面的源代碼中我們可以發(fā)現(xiàn)emptylist類并沒有重寫父類相應(yīng)的add()或者remove()方法,那么當(dāng)調(diào)用空集合的add()方法時(shí)將默認(rèn)調(diào)用abstractlist的add()方法,行,那么我們來看看父類abstractlist的add()方法是怎么實(shí)現(xiàn)的:
1
2
3
|
public void add( int index, e element) { throw new unsupportedoperationexception(); } |
1
2
3
|
public e remove( int index) { throw new unsupportedoperationexception(); } |
很遺憾,父類直接給你拋出unsupportedoperationexception異常,所以,小編認(rèn)為,通過collections創(chuàng)建的空集合不能添加或刪除元素也是合情合理的,因?yàn)槭强占下铮眨菫樯哆€要有添加刪除操作。下面說說這種方式的使用場景。
二、簡單使用場景
web開發(fā)中經(jīng)常使用rest + json的技術(shù)組合來進(jìn)行前后端交互,那么當(dāng)前端調(diào)用一個(gè)接口時(shí),接口有可能需要返回一個(gè)空的集合給到前端,比如你根據(jù)某個(gè)條件查數(shù)據(jù)庫得不到數(shù)據(jù)時(shí),那么此時(shí)collections.emptyxxx()就非常合適了,因?yàn)槭褂胣ew arraylist()的初始化還會(huì)占用相關(guān)的資源。
為了說明調(diào)用add()方法會(huì)拋出異常,下面寫個(gè)小測試:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public class removeiftest { private static list<object> list = collections.emptylist(); public static void main(string[] args) { list.add( "one1" ); list.add( "one2" ); list.add( 1 ); list.add( 2 ); list.add( new object()); system.err.println(arrays.tostring(list.toarray())); } } |
復(fù)制代碼程序輸出:
exception in thread "main" java.lang.unsupportedoperationexception
at java.util.abstractlist.add(unknown source)
at java.util.abstractlist.add(unknown source)
at com.example.removeiftest.main(removeiftest.java:17)
三、總結(jié)
總的來說,對(duì)于如何創(chuàng)建空集合的問題我們不需要糾結(jié),重要的我們要記住通過collections.emptyxxx()創(chuàng)建的空集合不能執(zhí)行添加刪除操作以及其中的原理,避免以后犯錯(cuò),不過其實(shí)即使你使用錯(cuò)了,調(diào)試幾遍你的代碼估計(jì)也就會(huì)把問題發(fā)現(xiàn)出來,只不過這篇文章能幫你省去這個(gè)發(fā)現(xiàn)bug的過程啦!
好了,以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對(duì)服務(wù)器之家的支持。
原文鏈接:https://juejin.im/post/5b29fdd16fb9a00e65266550