Java的怪异行为阵 [英] Java weird array behavior

查看:110
本文介绍了Java的怪异行为阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这个作品:

int[] array = {1, 2, 3};

但这并不:

int[] array;
array = {1, 2, 3};

如果我有一个数组实例变量,我想在我的构造函数来初始化它肯定我没有去。

If I have an array instance variable and I want to initialize it in my constructor surely I don't have to go

array = new int[3];
array[0] = 1;
array[1] = 2;
array[2] = 3;

我觉得我失去了一些东西?

I feel like I'm missing something here?

推荐答案

{...} 构建这里被称为Java中的数组初始化。它是一种特殊的速记即只在特定的语法构造可用

The {...} construct here is called an array initializer in Java. It is a special shorthand that is only available in certain grammatical constructs:

这是数组初始化的可在声明中指定,或作为数组创建前pression的一部分,创建一个数组并提供一些初始值。 [...]数组初始化写成逗号分隔的前pressions列表,括在大括号{ }

JLS 10.6 Array Initializers

An array initializer may be specified in a declaration, or as part of an array creation expression, creating an array and providing some initial values. [...] An array initializer is written as a comma-separated list of expressions, enclosed by braces "{" and "}".

按规定,你只能用这种速记无论是在声明或数组创建前pression。

As specified, you can only use this shorthand either in the declaration or in an array creation expression.

int[] nums = { 1, 2, 3 };       // declaration

nums = new int[] { 4, 5, 6 };   // array creation

这就是为什么以下不会编译:

This is why the following does not compile:

// DOES NOT COMPILE!!!
nums = { 1, 2, 3 };

// neither declaration nor array creation,
// array initializer syntax not available

还要注意的是:


  • 接着后面的逗号可能会出现;它将被忽略

  • 您可以的的,如果你初始化元素类型本身是一个数组的数组初始化

  • A trailing comma may appear; it will be ignored
  • You can nest array initializer if the element type you're initializing is itself an array

下面是一个例子:

    int[][] triangle = {
            { 1, },
            { 2, 3, },
            { 4, 5, 6, },
    };
    for (int[] row : triangle) {
        for (int num : row) {
            System.out.print(num + " ");
        }
        System.out.println();
    }

上面打印:

1 
2 3 
4 5 6 

另请参见


  • Java教程/螺母和螺栓/阵列

  • java.util中。阵列 - 有许多阵列相关的实用方法,如等于的toString

  • See also

    • Java Tutorials/Nuts and Bolts/Arrays
    • java.util.Arrays - has many array-related utility methods like equals, toString, etc
    • 这篇关于Java的怪异行为阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆