2010-07-08 39 views

回答

61

編號

ArrayList可以是空的(或者作爲項的空值)不爲空。它會被認爲是空的。您可以檢查空虛的ArrayList有:

ArrayList arrList = new ArrayList(); 
if(arrList.isEmpty()) 
{ 
    // Do something with the empty list here. 
} 

或者,如果你想創建檢查只有零點一個ArrayList的方法:

public static Boolean ContainsAllNulls(ArrayList arrList) 
{ 
    if(arrList != null) 
    { 
     for(object a : arrList) 
      if(a != null) return false; 
    } 

    return true; 
} 
+3

爲什麼不返回布爾值(對象)而不是布爾(原始類型)? – 2010-07-08 16:10:23

+0

你可以給我一個例子,如何創建一個空的arrayList? – Venki 2012-05-24 17:46:17

1

沒有,因爲它包含的項目必須有它的一個實例。它的項目是空是無關緊要的,所以statment((ArrayList的)!= NULL)==真

20

arrayList == null如果沒有分配給變量arrayListArrayList的實例(注意,類大寫在前和小寫變量)。

如果,在任何時候,你做arrayList = new ArrayList()然後arrayList != null,因爲所指向的類的實例ArrayList

如果你想知道,如果列表是空的,就

if(arrayList != null && !arrayList.isEmpty()) { 
//has items here. The fact that has items does not mean that the items are != null. 
//You have to check the nullity for every item 

} 
else { 
// either there is no instance of ArrayList in arrayList or the list is empty. 
} 

如果你不如果您的列表中沒有空項目,我建議您擴展ArrayList類,例如:

public class NotNullArrayList extends ArrayList{ 

@Override 
public boolean add(Object o) 
    { if(o==null) throw new IllegalArgumentException("Cannot add null items to the list"); 
     else return super.add(o); 
    } 
} 

或者,也許你可以擴展它以在你自己的類中有一個方法,重新定義「空列表」的概念。

public class NullIsEmptyArrayList extends ArrayList{ 

@Override 
public boolean isEmpty() 
    if(super.isEmpty()) return true; 
    else{ 
    //Iterate through the items to see if all of them are null. 
    //You can use any of the algorithms in the other responses. Return true if all are null, false otherwise. 
    //You can short-circuit to return false when you find the first item not null, so it will improve performance. 
    } 
} 

最後兩個方法是更面向對象的,更優雅和可重複使用的解決方案。

更新與傑夫建議IAE而不是NPE。

+0

好的建議!我會在NotNullArrayList示例中使用IllegalArgumentException而不是NPE。 – Jeff 2010-07-08 13:24:00

+0

傑夫,很好的建議。我改變了它。 – pakore 2010-07-08 13:56:59

4

不,這是不行的。你將能夠做的最好的是通過所有的值進行迭代,並自己去查他們:通過編寫一個簡單的測試用例

boolean empty = true; 
for (Object item : arrayList) { 
    if (item != null) { 
     empty = false; 
     break; 
    } 
} 
+0

對於包含單個空值的列表,這將返回false,因此可能不會。 – 2010-07-08 12:48:50

+0

@Mark謝謝,修正。似乎標題'空ArrayList等於空'扔我。 – krock 2010-07-08 12:55:41

0

首先,你可以自己驗證這一點!

空的ArrayList(用null作爲其項目)

其次,如果ArrayList中是空的,這意味着它是真的,也不能有NULL或非NULL事情元素。

三,

List list = new ArrayList(); 
    list.add(null); 
    System.out.println(list == null) 

將打印錯誤。

2

就像零是一個數字 - 只是一個不代表的數字 - 空的列表仍然是一個列表,只是一個沒有任何內容的列表。 null根本沒有名單;因此它與空列表不同。

同樣,包含空項目的列表是一個列表,並且是而不是的一個空列表。因爲它裏面有物品;這些項目本身都是空的並不重要。作爲一個例子,列表中有三個空值,沒有別的:它的長度是多少?它的長度是3.空列表的長度是零。當然,null沒有長度。

0

如果你想檢查數組中是否包含空值的項目,使用此:

private boolean isListOfNulls(ArrayList<String> stringList){ 
    for (String s: stringList) 
     if(s != null) return false; 
    return true; 
} 

您可以取代<String>與相應的類型,請ArrayList