简体   繁体   中英

How to check if array is null or if the array contents are null

What is the best way to check if array is null value or if the array contents are null in combination in 1 statement in Java 6:

if ((myArray[0] != null) || (myArray[1] != null) || (myArray!= null)) {
    ...
}

Firstly, check if the array is not null itself. If the array is null , it makes no reason to iterate its elements since Java will throw the NullPointerException upon access to it:

if (myArray != null) {
    // ...
}

Then inside the body of the condition iterate through all its elements and check if one of them is null .

boolean hasNull = false;
for (int i=0; i<myArray.length; i++) {
    if (myArray[i] == null) {
        hasNull = true;
        break; // to terminate the iteration since there is no need to iterate more
    } 
}

This one-line solution (thanks for the warning from @Napstablook). The condition is evaluated as true if the array itself is null or one of its element is null :

if !(myArray != null && myArray[0] != null && myArray[1] != null) { ... }

Be aware that the && operator works that if the left side is evaluated as false , it stops evaluating the rest of the condition because it will not affect the result. The same does || but with true . However, I suggest you avoid this solution since the index might overflow. Better use the for-loop mentioned above.

To have it check for any value, I'd use allMatch . It's also important to check for array != null first, otherwise you'll get an Exception if it is.

if (array == null || Arrays.stream(array).allMatch(Objects::isNull)) 

Note that this won't work with java prior to version 8, OP edited his requirements after I posted the answer

Check if Array is null:

String array[] = null;
if (array == null) {
  System.out.println("array is null");
}

Check if array is Empty:

array = new int[0];
if (array.length == 0) {
  System.out.println("array is empty");
}

Check for null at the same time:

int[] array = ...;
if (array.length == 0) { } // no elements in the array

if (array == null || iarray.length == 0) { }

Try this

 if (myArray == null || Arrays.stream(myArray).allMatch(element-> element==null)) {}

Edit- For java 6, I really don't see this happening in one line. You can try this if one line is not necessary

  boolean isNull = true;
    if(myArray==null){
        System.out.println("array is null");
    }else{
        for(Integer element: myArray){
            if(element!=null){
                System.out.println("array is not null");
                isNull=false;
                break;
            }
        }
        if(isNull)
            System.out.println("Array is null");
    }

for example this

boolean isNullOrContainsNull = array == null || Arrays.asList(array).contains(null);

checks in a line whether the array is null or contains null elements

If you want to check whether the array is null or empty or all elements are null take

boolean containsNothingUseful = array == null
        || array.length == 0
        || !new HashSet<String>(Arrays.asList(array))
            .retainAll(Arrays.asList((String)null));

(assuming a String[] array)

Uses the Collection#retainAll() method which returns true when there were other values present, ie the inverse of "containsOnly"

Using this one liner is actually fairly inefficient and one better uses a method like below which doesn't create lots of temporary objects and mutates collections etc.

public static boolean containsNothingUseful(String[] array) {
    if (array == null || array.length == 0)
        return true;
    for (String element : array) {
        if (element != null)
            return false;
    }
    return true;
}

// ...
if (containsNothingUseful(myArray)) { .. }

Instead Itreating Manullay the array, re use the existing collection for this case.

  1. Convert Array Into List
  2. Check Null is present in list or not using contains() method;

Please find the sample code:

public static void main(String[] args) {
        Integer[] array = new Integer[3];

        array[0] = 1;
        array[1] = null;
        array[2] = 2;

        System.out.println(Arrays.asList(array).contains(null));
    }

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