空ArrayList等于null

Glo*_*tor 31 java arrays arraylist

是空的Arraylist(以null为其项)被视为null?所以,基本上下面的陈述是正确的:

if (arrayList != null) 
Run Code Online (Sandbox Code Playgroud)

谢谢

Jus*_*ner 70

没有.

ArrayList可以为空(或使用null作为项)并且不为null.它会被认为是空的.你可以检查我的空ArrayList:

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

或者,如果要创建一个检查仅具有空值的ArrayList的方法:

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

    return true;
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么不返回布尔(基本类型)而不是布尔(对象)? (3认同)

pak*_*ore 22

arrayList == null如果没有ArrayList为该变量分配类的实例arrayList(请注意类的upercase和变量的小写).

如果,在任何时候,你做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.
}
Run Code Online (Sandbox Code Playgroud)

如果您不想在列表中使用空项,我建议您使用自己的类扩展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);
    }
}
Run Code Online (Sandbox Code Playgroud)

或者也许你可以扩展它以在你自己的类中有一个方法来重新定义"空列表"的概念.

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.
  }
}
Run Code Online (Sandbox Code Playgroud)

最后两种方法是面向对象,更优雅和可重用的解决方案.

更新了Jeff建议IAE而不是NPE.


kro*_*ock 5

不,这不行.您可以做的最好的事情是迭代所有值并自己检查:

boolean empty = true;
for (Object item : arrayList) {
    if (item != null) {
        empty = false;
        break;
    }
}
Run Code Online (Sandbox Code Playgroud)