【问题标题】:Why is result of creating a new int array equals to 5? [duplicate]为什么创建一个新的 int 数组的结果等于 5? [复制]
【发布时间】:2019-10-27 14:43:52
【问题描述】:

这个

new int[][] { { 1, 2, 7 }, { 3, 4, 5 } }[1][2];

结果是一个普通的 int 等于 5。

我看到这个数组初始化了一些我不知道的方法。所以,我想如果你能解释一下它的含义和目的,一切都会变得清晰。

【问题讨论】:

    标签: java arrays


    【解决方案1】:

    new int[][] { { 1, 2, 7 }, { 3, 4, 5 } } 创建一个数组。 [1] 访问第二行 {3, 4, 5} 然后 [2] 给你五个。相当于

    int[][] t = { { 1, 2, 7 }, { 3, 4, 5 } };
    int x = t[1][2];
    

    (没有t)。

    【讨论】:

      【解决方案2】:

      new int[][] { { 1, 2, 7 }, { 3, 4, 5 } } 是一个数组字面量。正如1 表示“整数1”和"foo" 表示“字符串"foo"”一样,new int[][] { { 1, 2, 7 }, { 3, 4, 5 } } 表示“整数数组数组{ { 1, 2, 7 }, { 3, 4, 5 } }”。

      当你有一个数组时,你可以索引它。让我们将我们的匿名整数数组数组称为harvey

      int[][] harvey = new int[][] { { 1, 2, 7 }, { 3, 4, 5 } }
      

      现在harvey[1] 是“整数数组{ 3, 4, 5}”,如果我们再次索引它,harvey[1][2] 是该数组的第三个值5

      但是无论你在哪里可以使用harvey,你都可以替换它的值;这就是你的表达方式。

      【讨论】:

        猜你喜欢
        • 2017-07-15
        • 2018-03-08
        • 1970-01-01
        • 1970-01-01
        • 2020-10-17
        • 2018-08-26
        • 1970-01-01
        • 2013-02-10
        • 1970-01-01
        相关资源
        最近更新 更多