java中数组如何赋值
数组赋值的几种方法
在Java中,数组赋值可以通过多种方式实现,具体取决于数组的类型和初始化状态。
直接初始化赋值
声明数组时直接赋予初始值,适用于已知所有元素值的情况:
int[] numbers = {1, 2, 3, 4, 5};
String[] names = {"Alice", "Bob", "Charlie"};
使用new关键字初始化后赋值
先创建指定长度的数组,再通过索引逐个赋值:

double[] prices = new double[3];
prices[0] = 9.99;
prices[1] = 19.99;
prices[2] = 29.99;
循环批量赋值
通过循环结构为数组元素批量赋值,适用于规律性数据:
int[] squares = new int[10];
for (int i = 0; i < squares.length; i++) {
squares[i] = i * i;
}
使用Arrays类方法

利用java.util.Arrays工具类进行赋值或填充:
char[] letters = new char[5];
Arrays.fill(letters, 'A'); // 全部填充为'A'
int[] source = {1, 2, 3};
int[] target = new int[3];
System.arraycopy(source, 0, target, 0, source.length); // 数组复制
多维数组赋值
多维数组可采用嵌套方式进行赋值:
int[][] matrix = {{1, 2}, {3, 4}, {5, 6}};
// 或分步赋值
String[][] chessboard = new String[8][8];
chessboard[0][0] = "Rook";
注意事项
- 基本类型数组未显式赋值时,元素会默认初始化为0/false等
- 对象类型数组未赋值时元素为null
- 数组索引从0开始,赋值时需注意边界避免ArrayIndexOutOfBoundsException






