【问题标题】:how to check the string array is empty or null android? [duplicate]如何检查字符串数组是空的还是空的android? [复制]
【发布时间】:2013-05-25 15:01:12
【问题描述】:

我是 Java 新手。我无法检查空值。你能告诉我这个吗? 我有没有元素的字符串数组。

我试过这段代码

String[] k = new String[3];
if(k==null){
    System.out.println(k.length);
}

【问题讨论】:

标签: java android


【解决方案1】:
String k[] = new String[3];

if(k.length == 0 ){

System.out.println("Null");
}

如果数组中没有元素,则显示null。

【讨论】:

    【解决方案2】:

    非常准确

    if(k!=null && k.length>0){
        System.out.println(k.length);
    }else
        System.out.println("Array is not initialized or empty");
    

    k!=null 会检查 array 不是 null。而StringArray#length>0return 不为空[您也可以在检查长度之前修剪丢弃空格]。

    一些相关的热门问题 -

    【讨论】:

      【解决方案3】:
      if (myArray == null)
      
         System.Console.WriteLine("array is not initialized");
      
      else if (myArray.Length < 1)
      
         System.Console.WriteLine("array is empty");
      

      【讨论】:

        【解决方案4】:

        null 数组和空数组之间有一个关键区别。这是对null 的测试。

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

        这里的“空”没有官方含义。我选择将空定义为具有 0 个元素:

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

        “空”的另一种定义是如果所有元素都是null

        Object arr[] = new Object[10];
        boolean empty = true;
        for (int i=0; i<arr.length; i++) {
          if (arr[i] != null) {
            empty = false;
            break;
          }
        }
        

        Object arr[] = new Object[10];
        boolean empty = true;
        for (Object ob : arr) {
          if (ob != null) {
            empty = false;
            break;
          }
        }
        

        Reference

        【讨论】:

          【解决方案5】:

          我认为你可以使用这个:

          if(str != null && !str.isEmpty())
          

          更新

          更好的解决方案是这个:

          TextUtils.isEmpty(str)
          

          【讨论】:

          • java中没有字符串数组的'isEmpty()'方法。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-01-23
          • 1970-01-01
          • 2012-05-07
          • 1970-01-01
          • 2014-12-20
          相关资源
          最近更新 更多