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 中初始化一个数组?
基础教程推荐
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Struts2 URL 无法访问 2022-01-01
