2010-07-08 37 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