有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java初始化的数组是否保留其顺序?

假设我初始化了一个数组,如下所示:

int[] anArray = { 
    100, 200, 300,
    400, 500, 600, 
    700, 800, 900, 1000
};

是否保证元素总是以我在初始化时键入的相同顺序插入?例如:100,200,300,400,500,600,700,...,1000


共 (5) 个答案

  1. # 1 楼答案

    是的,这由规范保证(见JLS 10.6):

    The variable initializers immediately enclosed by the braces of the array initializer are then executed from left to right in the textual order they occur in the source code. The n'th variable initializer specifies the value of the n-1'th array component.

  2. # 2 楼答案

    是的

    您发布的代码与此相同:

    int[] anArray = { 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000 };
    

    这样做的目的是创建一个arrayintegers,其中100位于位置0,200至位置1300至位置2400至位置3,以此类推

    每次对每个阵列都是一样的

  3. # 3 楼答案

    Is it guaranteed that the elements will be always inserted in the same order I've typed on the initialization?

  4. # 4 楼答案

    是的,如果数组正在改变值的位置,那么现代的大多数程序将无法工作

  5. # 5 楼答案

    简短回答:是的,如果你像那样初始化它,它们将按照初始化的顺序

    请参阅JLS:

    The variable initializers immediately enclosed by the braces of the array initializer are then executed from left to right in the textual order they occur in the source code. The n'th variable initializer specifies the value of the n-1'th array component

    https://docs.oracle.com/javase/specs/jls/se8/html/jls-10.html#jls-10.6