简体   繁体   English

如何检查数组是否为空或数组内容是否为空

[英]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: 什么是检查数组是最好的方式null值,或者如果数组内容是null的组合在Java 6中1个语句:

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

Firstly, check if the array is not null itself. 首先,检查数组本身是否不为null If the array is null , it makes no reason to iterate its elements since Java will throw the NullPointerException upon access to it: 如果数组为null ,则没有理由对其元素进行迭代,因为Java在访问它时将抛出NullPointerException

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

Then inside the body of the condition iterate through all its elements and check if one of them is null . 然后在条件主体内部遍历其所有元素,并检查其中之一是否为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). 这种单行解决方案(感谢@Napstablook的警告)。 The condition is evaluated as true if the array itself is null or one of its element is null : 条件被评估为true ,如果数组本身是null或它的元件之一是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. 请注意, &&运算符的作用是,如果左侧被评估为false ,则它将停止评估其余条件,因为它不会影响结果。 The same does || || but with true . 但是true However, I suggest you avoid this solution since the index might overflow. 但是,我建议您避免这种解决方案,因为索引可能会溢出。 Better use the for-loop mentioned above. 最好使用上面提到的for-loop

To have it check for any value, I'd use allMatch . 为了让它检查任何值,我将使用allMatch It's also important to check for array != null first, otherwise you'll get an Exception if it is. 首先检查数组!= null也很重要,否则,将得到Exception。

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 请注意,这不适用于版本8之前的Java,在我发布答案后,OP编辑了他的要求

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: 同时检查null:

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. 编辑-对于Java 6,我真的看不到这一行。 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 在一行中检查数组是否为null或包含null元素

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) (假设一个String[]数组)

Uses the Collection#retainAll() method which returns true when there were other values present, ie the inverse of "containsOnly" 使用Collection#retainAll()方法,该方法在存在其他值(即与“ containsOnly”相反Collection#retainAll()时返回true

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. 代替Itreating Manullay数组,在这种情况下重新使用现有的集合。

  1. Convert Array Into List 将数组转换为列表
  2. Check Null is present in list or not using contains() method; 检查null是否存在于列表中或不使用contains()方法;

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));
    }

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

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