How to initialize an array in Java?(如何在 Java 中初始化一个数组?)
问题描述
我正在像这样初始化一个数组:
I am initializing an array like this:
public class Array {
int data[] = new int[10];
/** Creates a new instance of Array */
public Array() {
data[10] = {10,20,30,40,50,60,71,80,90,91};
}
}
NetBeans 在这一行指出一个错误:
NetBeans points to an error at this line:
data[10] = {10,20,30,40,50,60,71,80,90,91};
我该如何解决这个问题?
How can I solve the problem?
推荐答案
data[10] = {10,20,30,40,50,60,71,80,90,91};
以上内容不正确(语法错误).这意味着您正在为 data[10]
分配一个数组,该数组只能包含一个元素.
The above is not correct (syntax error). It means you are assigning an array to data[10]
which can hold just an element.
如果要初始化数组,请尝试使用 数组初始化器:
If you want to initialize an array, try using Array Initializer:
int[] data = {10,20,30,40,50,60,71,80,90,91};
// or
int[] data;
data = new int[] {10,20,30,40,50,60,71,80,90,91};
注意两个声明之间的区别.将新数组分配给已声明的变量时,必须使用 new
.
Notice the difference between the two declarations. When assigning a new array to a declared variable, new
must be used.
即使改正了语法,访问data[10]
还是不正确(只能访问data[0]
到data[9]
因为 Java 中的数组索引是从 0 开始的).访问 data[10]
将抛出 ArrayIndexOutOfBoundsException.
Even if you correct the syntax, accessing data[10]
is still incorrect (You can only access data[0]
to data[9]
because index of arrays in Java is 0-based). Accessing data[10]
will throw an ArrayIndexOutOfBoundsException.
这篇关于如何在 Java 中初始化一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Java 中初始化一个数组?


基础教程推荐
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 降序排序:Java Map 2022-01-01