Java 我们可以在运行时提到数组大小吗?
根据我的理解,我们需要在编译时定义数组大小。但根据下面的代码,我们似乎也可以在运行时提供数组大小Java 我们可以在运行时提到数组大小吗?,java,arrays,Java,Arrays,根据我的理解,我们需要在编译时定义数组大小。但根据下面的代码,我们似乎也可以在运行时提供数组大小 public class Test { public static void main(String args[]){ Scanner scan = new Scanner(System.in); int length= scan.nextInt(); int arr[] = new int[length]; fo
public class Test {
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
int length= scan.nextInt();
int arr[] = new int[length];
for(int i =0; i < length;i++){
arr[i]=i;
}
for(int data : arr){
System.out.println("Data: "+data);
}
}
}
如果有人能向我解释一下这种行为,我将不胜感激。是的,您可以将int类型的任何内容传递给新的T[]构造函数,例如,您也可以这样做:
int userInput = new Scanner(System.in).nextInt();
int len = 12 + 14 * 3 / userInput;
byte[] arr = new byte[len];
// arr has now the size as specified by len.
你可以这样做-
您的程序实际上并不介意在该框中写什么,只要它是数组数据结构的合理数字-小于Integer.MAX_值且在开始运行之前为非负。
所以如果你写
int[] box = new int[4];
在构建之前,Java不知道数组的长度是4。事实上,在代码运行之前,数组甚至都不会初始化
在这种情况下,可以使用变量表示数组长度,只要程序运行该行代码时,变量是数组长度的合理数字。在Java中,可以创建一个数组,其大小在运行时确定 从您的代码:
int arr[] = new int[length];
当在运行时到达这一行时,程序分配一个整数数组,其大小等于变量长度的当前值,并通过arr引用它,但不确定有什么需要解释。您的理解不正确。不是在编译时定义它,而是在某个点定义它。在上面的例子中,当执行代码并创建arr[]变量时,它将定义大小。然后将数组固定为该大小,但在创建之前不必硬编码该大小。