【问题标题】:How to detect if an index exists in an array (String[])?如何检测数组(String[])中是否存在索引?
【发布时间】:2013-06-10 06:33:31
【问题描述】:

当字符串中包含感叹号时,我正在使用str.split("!") 将字符串拉成两半。通过代码设置的方式,如果没有感叹号,我将得到一个 1 索引数组,如果有,我将得到一个 2 索引数组。

代码:

String file, macroName;

String[] fileAndMacro = string.split("!");
if(fileAndMacro[0] != null)
    file = new File(fileAndMacro[0]);
if(fileAndMacro[1] != null)
    macroName = fileAndMacro[1];

如果我输入一个带有感叹号的字符串,它会起作用。例如"test!string" 将返回fileAndMacro[0] = "test"fileAndMacro[1] = "string"

问题是当我没有感叹号时(你们中的一些人可能从我的代码中看出)。我只是得到一个ArrayIndexOutOfBoundsException。因此,显然空检查并不能解决问题。如果没有为要存储的值分配空间,考虑到内存中不能有空值,这是有道理的。

尽管我对此有所了解,但我不确定如何检查第二个索引是否存在。如何实时查看索引是否存在?

【问题讨论】:

  • 您不需要检查数组元素是否为空:它们永远不会为空。
  • 真的,所以像array[0] = null 这样的东西会抛出错误之类的吗?
  • 不,String.split() 不会发生类似的事情永远 ;) 如果数组为空,尝试访问它会抛出 ArrayIndexOutOfBoundsException。 Java中的数组是在初始化时分配的,不可调整大小,零长度数组是可能的
  • 啊,好吧,我明白你的意思了。

标签: java arrays


【解决方案1】:

你需要检查你的数组的长度,所以:

if(fileAndMacro.length > 1)
   macroName = fileAndMacro[1];

通过访问不存在的索引,您将访问内存中不属于您创建的数组(实际上是在split() 方法中创建的)的其他一些空间,这就是您得到异常的原因。

【讨论】:

    【解决方案2】:

    只需测试fileAndMacro.length。如果是 2 或更大,则至少有一个感叹号。

    【讨论】:

    • 不幸的是,如果您在没有整数参数的情况下使用 .split(),这并不完全正确...拆分 "!" 也会得到一个零长度数组。您需要将 negative 参数传递给.split(),以便它真正按书分开。
    【解决方案3】:

    您可以使用其长度属性array.length检查数组的长度

    if (array.length  < 2){
        //perform some operation you want
    
    }
    

    【讨论】:

      【解决方案4】:

      这个问题也适用于 Kotlin。所以,这里是 Kotlin 的解决方案:

      if (index in myArray.indices) {
        // index is valid
      }
      

      其他解决方案:

      myArray.getOrNull(index)?.let { element ->
        // index is valid; use the element
      }
      
      if (myList.getOrNull(index) != null) {
        // index is valid
      }
      
      if (index in 0..myArray.lastIndex) {
        // index is valid
      }
      
      if (index >= 0 && index <= myArray.lastIndex) {
        // index is valid
      }
      

      收藏有another similar question

      【讨论】:

        猜你喜欢
        • 2013-03-21
        • 1970-01-01
        • 2020-05-26
        • 2012-10-17
        • 2010-09-20
        • 2012-03-10
        • 1970-01-01
        • 2017-11-19
        • 2010-10-22
        相关资源
        最近更新 更多