【问题标题】:How to check if array is null or if the array contents are null如何检查数组是否为空或数组内容是否为空
【发布时间】:2018-06-07 12:55:54
【问题描述】:

在Java 6中的1条语句中检查数组是否为null值或数组内容是否为null的最佳方法是:

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

【问题讨论】:

  • myArray != null放在第一位,你可能想用&&
  • 看看这个相关的问题:How can I check whether an array is null / empty?。我想不出一种方法可以在 Java 6 的一个简洁语句中做到这一点,但该问题有一些答案显示了如何检查(不止一行)。
  • stackoverflow.com/questions/2369967/… 的答案分为语句和另一种方法。我需要能够将它们组合成 1 个语句
  • 你为什么还在使用 Java 6?在过去 3 年多的时间里,当 Oracle 停止发布安全更新时,它一直不受支持。您正在向安全漏洞敞开大门。
  • 那么@AndyTurner 的评论不是已经完成了吗? if (array == null || array[0] == null && array[1] == null) { // array is null or contains only nulls }

标签: java arrays nullpointerexception


【解决方案1】:

首先,检查数组本身是否不是null。如果数组是null,则没有理由迭代其元素,因为Java 将在访问它时抛出NullPointerException

if (myArray != 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
    } 
}

这个单行解决方案(感谢@Napstablook 的警告)。如果数组本身是null 或其元素之一是null,则条件被评估为true

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

请注意,&amp;&amp; 运算符的工作原理是,如果左侧计算为 false,它将停止计算其余条件,因为它不会影响结果。 || 也是如此,但 true 也是如此。但是,我建议您避免使用此解决方案,因为索引可能会溢出。最好使用上面提到的for-loop

【讨论】:

  • OP 想要检查数组是否为空或数组中的所有元素是否为空。请参阅 post- 或者如果数组内容为空
【解决方案2】:

要让它检查任何值,我会使用allMatch。首先检查 array != null 也很重要,否则你会得到一个异常。

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

请注意,这不适用于版本 8 之前的 java,OP 在我发布答案后编辑了他的要求

【讨论】:

    【解决方案3】:

    检查数组是否为空:

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

    检查数组是否为空:

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

    同时检查null:

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

    【讨论】:

      【解决方案4】:

      试试这个

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

      Edit- 对于 java 6,我真的没有看到这发生在一行中。如果不需要一行,你可以试试这个

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

      【讨论】:

        【解决方案5】:

        而不是 Itreating Manullay 数组,在这种情况下重新使用现有集合。

        1. 将数组转换为列表
        2. 使用 contains() 方法检查 Null 是否存在于列表中;

        请找到示例代码:

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

        【讨论】:

        • 这已经在another answer 中提出过,但它不满足Op 的要求。他们想知道所有个条目是否是null,而不是任何个条目。
        【解决方案6】:

        例如这个

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

        在一行中检查数组是否为空或包含空元素

        如果要检查数组是否为空或为空或所有元素是否为空

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

        (假设一个String[] 数组)

        使用 Collection#retainAll() 方法,当存在其他值时返回 true,即“containsOnly”的倒数

        使用这种方法实际上是相当低效的,最好使用下面这样的方法,它不会创建大量临时对象和改变集合等。

        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)) { .. }
        

        【讨论】:

        • 如果数组中至少有一个元素为空,则返回 true。 OP 想要检查所有元素是否为空。
        • @Napstablook 是的,我也为此添加了一个版本
        猜你喜欢
        • 2011-11-04
        • 2011-01-23
        • 1970-01-01
        • 1970-01-01
        • 2017-09-13
        • 1970-01-01
        • 2022-10-20
        • 2012-07-29
        相关资源
        最近更新 更多