【问题标题】:Is arithmetic allowed in a Java array subscript? [closed]Java数组下标中是否允许算术? [关闭]
【发布时间】:2017-05-15 19:31:12
【问题描述】:

通过计算调用行中的下标来访问数组索引中的数据是否合法?像这样:

int[] foo = new int[10];
int bar = foo[3-1];    //attempts to set bar = foo[2]

【问题讨论】:

  • 你为什么不试试呢?
  • 检查起来比发个问题容易。我确定
  • 我不在编译器附近。为未来程序员的利益提出同样问题的问题真的那么可笑吗?
  • 未来的程序员会自己尝试。
  • @Cody ideone.com 如果您在 SO 上可用。或者,当然,the language spec

标签: java arrays


【解决方案1】:

只要下标中的表达式计算结果为int,它就会起作用。

【讨论】:

    【解决方案2】:

    是的。任何以int 结尾的计算都可以在数组访问中使用。 (当然,如果它超出数组范围或负数,它会抛出,但它会编译。)The JLS specifies this behavior

    【讨论】:

      【解决方案3】:

      你可以在那些 [] 之间加上任何你编译时的结果是一个整数......其他任何东西都不会编译

      public static void main(String[] args) {
          int[] foo = { 1, 0, 1, 3 };
          int bar = foo[3 - 1];
          bar = foo[1.0];// invalid since is a double
          bar = foo[1L];// invalid since is a long
          bar = foo[args.length];// valid
          bar = foo[3 - 1];// valid
          bar = foo[Double.valueOf(0).intValue()];// valid
          bar = foo[x];// valid if x is an int
      }
      

      【讨论】:

        【解决方案4】:

        是的,这是合法的,除非您的计算没有错误并且结果是int,因为如果计算错误(大于或小于数组的大小),这会引导您进入错误java.lang.ArrayIndexOutOfBoundsException: xxx ),所以要小心。

        【讨论】:

          猜你喜欢
          • 2023-03-04
          • 2013-05-19
          • 1970-01-01
          • 2013-01-19
          • 1970-01-01
          • 1970-01-01
          • 2014-04-30
          • 1970-01-01
          • 2010-12-03
          相关资源
          最近更新 更多