gpt4 book ai didi

java - 这个 for 循环如何知道这个数组数据结构从一开始有多长?

转载 作者:太空宇宙 更新时间:2023-11-04 12:17:12 24 4
gpt4 key购买 nike

我试图弄清楚数组如何知道 for 循环中第一次运行 System.out.println 时总共有 15 个索引,以及它从哪里知道它的确切位置。

当for循环仍在执行时,它似乎知道索引的总数,并且我认为一旦创建了数组,就无法更改它。数组在构造时是否处于临时状态,或者答案比我所做的简单得多?

我正在猜测可能的答案,但我不确定。请帮忙!预先感谢您。

我使用此代码的唯一目的是与用于创建它的代码相比,评估底部的结果输出,并确定此特定的 for 循环如何构造数组。

import java.util.Arrays;

public class DataStructureMain {

public static void main(String[] args) {

class DataStructure {

//Create an array
private final static int SIZE = 15;
private int[] anArrayOfInts = new int[SIZE];

public DataStructure() {

//Fill the array with ascending integer values
for (int i = 0; i < SIZE; i++) {
anArrayOfInts[i] = i;
//I put this next line in here to see how the code
//executes each run of the for-loop
System.out.println(Arrays.toString(anArrayOfInts));
}
}
}

//
//
DataStructure dS = new DataStructure();

}

}

产生这个:


[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 0, 0, 0]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 0, 0]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 0]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 0]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

最佳答案

你设置
SIZE = 15;
然后你使用相同的变量来构造数组
private int[] anArrayOfInts = new int[SIZE];
一旦创建,其大小就固定了。
然后使用相同的变量来限制迭代次数
for (int i = 0; i < SIZE; i++)

或者您可以使用:
for (int i = 0; i < anArrayOfInts.length ; i++)
这会给你相同的结果。

关于java - 这个 for 循环如何知道这个数组数据结构从一开始有多长?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39261871/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com