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 中初始化一个数组?
基础教程推荐
- 将 double 转换为 Int,向下舍入 2022-01-01
- JPA惰性列表上的流 2022-01-01
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- 将 Windows 证书导入 Java 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
