检查java中字符串数组的大小或长度

时间:2011-03-05 18:16:59

标签: java

我有这个

String p[] = null;

我需要检查它的大小/长度是否为null。像

这样的东西
if (p.length == null)

但它不起作用。

7 个答案:

答案 0 :(得分:8)

您无法检查null的长度。另外,length会返回int,而null永远不会是if (p == null) { // There is no array at all. } else if (p.length == 0) { // There is an array, but there are no elements. } 。只是做

null

或者只是实例化它而不是保留它String[] p = new String[0];

if (p.length == 0) {
    // There are no elements.
}   

然后你可以这样做:

{{1}}

另见:

答案 1 :(得分:2)

if (p == null)

长度值是根据数组的大小计算的。如果数组为null,则只检查对象而不是长度。

答案 2 :(得分:2)

空引用没有长度。任何访问其任何成员的尝试都将导致NullPointerException

数组对象的长度为int,这意味着它可以是0,但不是null。数组类型的空引用与指向长度为零的数组对象的引用之间存在差异。

也许你想这样做:

if(p==null || p.length==0)

由于||是一个短路运算符,这将为空引用和长度为零的数组返回false,而不是抛出NullPointerException

答案 3 :(得分:1)

public boolean isUseless(String str)
{
    return str == null || str.length() == 0;
}

使用模式:

String s = null;
isUseless(s);

返回true

答案 4 :(得分:1)

如果引用为null,则不能对其进行任何操作,如访问其方法。我认为你真正需要的是

if (p == null) {
    // throw some exception
} else {
   if (p.length == 0) {
       // your logic goes here
   }
}

答案 5 :(得分:0)

您无法检查null个成员,这是不可能的,一旦您拥有String[] lengthcount的实际实例,为0,因为这是它们的默认值。

您可以将其初始化为

String[] p = new String[6];

然后,在您初始化后,您可以拨打p.length

答案 6 :(得分:-1)

就个人而言,我使用apache的commons lang lib中的ArrayUtils.getLength

检查nullity并返回0数组的null大小。