【问题标题】:How to check whether an array with a specific Index is empty?如何检查具有特定索引的数组是否为空?
【发布时间】:2018-07-15 10:24:57
【问题描述】:

我遵循了这个线程中提出的观点,但我收到错误“操作符未定义参数类型[...]”

How can I check whether an array is null / empty?

我的代码:

public class Test{

private int[] array = new int [5];

  public int method(int i) {
      for(int s = 0; s <= array.length; s++) {
          if( array[s] != null) { //I get the error in here even though the highest upvoted answer in the linked question recommends this solution. I obviously cant check it for 0, because the user input can be 0.
            array[s] = i;
          } else {
             method(i);
        }
      }
   }
}

谢谢!

【问题讨论】:

  • s &lt;= array.length总是错误的,因为您将尝试访问超出数组的边界(导致异常)
  • 另外,int[] 中不能有“空”值 - 默认值为 0,无法将其设置为 null。您的数组可以是 nulllength 为 0,您无能为力
  • 是的,没有想到这一点,但即使使用 array.length -1 修复它,我的其他问题仍然存在。

标签: java arrays int


【解决方案1】:

您会收到此错误,因为 int 是原始类型。在您的情况下,array[s] 返回 int 而不是 IntegerInt 不能是 null

如果您想检查 null,请将您的数组从 int[] 更改为 Integer[]

private Integer[] array = new Integer[5];

【讨论】:

    【解决方案2】:

    你有int的数组,它是原始类型,Java中的原始类型不能是null,所以编译器在检查它是否是null时会出错,如果你真的想要它,你可以使用Integer这是int 的包装类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-07
      • 1970-01-01
      • 2013-03-15
      • 2012-04-04
      • 2017-10-22
      • 2015-12-23
      • 1970-01-01
      相关资源
      最近更新 更多