java 数组如何赋值
数组赋值的几种方法
静态初始化 在声明数组的同时直接赋值,适用于已知元素值的情况:
int[] arr1 = {1, 2, 3, 4}; // 一维数组
String[][] arr2 = {{"a","b"}, {"c","d"}}; // 二维数组
动态初始化 先指定数组长度,再通过索引逐个赋值:

double[] arr = new double[3];
arr[0] = 1.1;
arr[1] = 2.2;
arr[2] = 3.3;
使用Arrays工具类
通过Arrays.fill()快速填充相同值:

char[] chars = new char[5];
Arrays.fill(chars, 'A'); // 全部赋值为'A'
System.arraycopy复制 复制已有数组内容到新数组:
int[] source = {1,2,3};
int[] target = new int[3];
System.arraycopy(source, 0, target, 0, source.length);
循环赋值 适用于需要计算或规律性赋值:
int[] squares = new int[10];
for(int i=0; i<squares.length; i++){
squares[i] = i * i;
}
注意事项
- 基本类型数组未赋值时元素为默认值(如int为0)
- 对象类型数组未赋值时元素为null
- 数组索引从0开始,越界访问会抛出ArrayIndexOutOfBoundsException
- 多维数组本质是数组的数组,每行长度可以不同






