【问题标题】:Need help understanding strange array syntax需要帮助理解奇怪的数组语法
【发布时间】:2014-01-21 16:25:03
【问题描述】:

我在一本书中找到了这一点,但我不明白它的作用:

int index = 1;
...
getArray() [index=2]++;

[index=2]++; 对我来说看起来很奇怪,但可以编译。更奇怪的是,如果 ++ 被删除,它就会变为无效,尽管据我所知, ++ 在这种情况下什么都不做(值总是2) .

那么,在这种情况下,post-increment 运算符的意义是什么(因为它不会增加值),为什么括号以及为什么只有在末尾添加 post-inc 时语句才合法?

谁能解释一下这个神秘的语法是什么以及它有什么作用?

【问题讨论】:

  • ++ 将增加一个数组元素。你检查了吗?

标签: java arrays


【解决方案1】:

让我们破解这段代码:

getArray() [index=2]++;

相当于:

int[] someArray = getArray();  // Assume that's an int[]
index = 2;
someArray[index]++;

最后一行相当于:

someArray[index] = someArray[index] + 1;

如果删除 ++,则第二个表达式不是有效语句。它只是变成:

getArray() [index];

你必须将它分配给一些 L-Value。

【讨论】:

  • 太棒了。 “L 值”是什么意思?
  • @alliteralmind 左值。意味着,一些变量来存储该数组索引的值。
  • @RohitJain 你的“相当于”是错误的。在原来的情况下,index=2 出现在getArray() 之后,所以你得到了index 的分配和getArray() 的评估错误的方式。我写了一个demo of the difference。第一个应该是int[] arr = getArray(); index = 2; arr[index]++;(然后第二个是多余的)。
【解决方案2】:

当然是无效的,你没有用它做任何事情。

getArray() [index=2]++;

为了演示,我会将getArray() 切换为myArray,后者具有{ 100, 200, 300, 400 }
比它等于:

myArray[2]++;

myArray[2] 现在将输出:301
index 将是:2

【讨论】:

    【解决方案3】:

    getArray() 必须返回一个数字数组(比如说ints),所以getArray() [index=2]++; 被剖析:

    int index = 2;
    int[] array = getArray();
    array[index] = array[index] + 1;
    

    【讨论】:

      【解决方案4】:
      package test1;
      public class Q30 {
          private static int[] x={10,20,30};
          public static int[] getArray(int[] y) {
              return y;
          }
      
          public static void main(String[] args) {
              int index = 1;
              getArray(x);
              for (int q:getArray(x)) {
                  System.out.print(q+" ");//10 20 30 
              }
      
             // try {
              getArray(x)[index = 2]++;
              //} catch (Exception e) {
              //}  //empty catch
              System.out.println();
              System.out.println("index = " + index);//index = 2
              for (int q:getArray(x)) {
                  System.out.print(q+" ");//10 20 31 
              }
      
          }
      }
      

      【讨论】:

      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 1970-01-01
      • 2011-05-04
      • 1970-01-01
      • 2017-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-13
      • 1970-01-01
      相关资源
      最近更新 更多