简体   繁体   中英

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. Something like

if (p.length == null)

But it does not work.

You cannot check length of null . Also, length returns an int which can never be null . 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 .

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.

A null reference does not have a length. Any attempt to access any of its members will result in a NullPointerException .

An array object has a length of type int , which means it can be 0 , but not 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 .

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

Usage pattern:

String s = null;
isUseless(s);

Returns true

if a reference is null, you can't do any operations on it like accessing its methods. 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.

You can initialize this as

String[] p = new String[6];

Then once you've initialized this you can call p.length

Personally, I use the ArrayUtils.getLength from the apache's commons lang lib.

It checks the nullity and returns a size ( 0 for a null array).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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