简体   繁体   English

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

[英]Checking the size or length of a string array in java

I have this 我有这个

String p[] = null;

I need to check whether its size/length is null or not. 我需要检查它的大小/长度是否为null Something like 就像是

if (p.length == null)

But it does not work. 但它不起作用。

You cannot check length of null . 您无法检查null长度。 Also, length returns an int which can never be null . 此外, length返回一个永远不能为nullint Just do 做就是了

if (p == null) {
    // There is no array at all.
} else if (p.length == 0) {
    // There is an array, but there are no elements.
}

Or just instantiate it instead of keeping it null . 或者只是实例化它而不是保持null

String[] p = new String[0];

Then you can do: 然后你可以这样做:

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

See also: 也可以看看:

if (p == null)

the length value is calculated from the size of the array. 长度值是根据数组的大小计算的。 If the array is null, then just check the object and not the length. 如果数组为null,则只检查对象而不是长度。

A null reference does not have a length. 空引用不具备的长度。 Any attempt to access any of its members will result in a NullPointerException . 任何访问其任何成员的尝试都将导致NullPointerException

An array object has a length of type int , which means it can be 0 , but not null . 数组对象的长度类型为int ,这意味着它可以是0 ,但不能为null There is a difference between a null reference of an array type and a reference pointing at an array object of length zero. 数组类型的空引用与指向长度为零的数组对象的引用之间存在差异。

Perhaps you want to do this: 也许你想这样做:

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

Since || || is a short-circuiting operator, this will return false for both null references and arrays of length zero, and not throw a NullPointerException . 是一个短路运算符,这将为null引用和长度为零的数组返回false ,而不是抛出NullPointerException

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

Usage pattern: 使用模式:

String s = null;
isUseless(s);

Returns true 返回true

if a reference is null, you can't do any operations on it like accessing its methods. 如果引用为null,则不能对其进行任何操作,如访问其方法。 what i think you really need is 我认为你真正需要的是

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

You can't check a null objects members, this isn't possible, and once you have an actual instance of the String[] the length and count will be 0 as this is their default value. 您无法检查null对象成员,这是不可能的,并且一旦您拥有String[]的实际实例,则lengthcount将为0,因为这是它们的默认值。

You can initialize this as 您可以将其初始化为

String[] p = new String[6];

Then once you've initialized this you can call p.length 然后,一旦你初始化了这个,你可以调用p.length

Personally, I use the ArrayUtils.getLength from the apache's commons lang lib. 就个人而言,我使用apache的commons lang lib中的ArrayUtils.getLength

It checks the nullity and returns a size ( 0 for a null array). 它检查nullity并返回一个大小( null数组为0 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM