在Java中,数组用于存储相同类型的数据。以下是存储值到Java数组中的几种方法:
直接赋值
对于基本类型数组,可以直接赋值:
int[] numbers = new int;
numbers = 10;
numbers = 20;
numbers = 30;
对于对象数组,赋值会指向对象引用:
String[] names = new String;
names = "John";
names = "Jane";
names = "Tom";
使用`Arrays.fill()`方法
可以将数组的所有元素填充为指定值:
int[] numbers = new int;
Arrays.fill(numbers, 10);
使用`System.arraycopy()`方法
可以将一个数组的部分或全部元素复制到另一个数组中:
int[] numbers1 = new int;
numbers1 = 10;
numbers1 = 20;
int[] numbers2 = new int;
System.arraycopy(numbers1, 1, numbers2, 0, 2);
请注意,Java数组的大小是固定的,一旦创建,不能改变其长度。如果需要动态改变大小,可以使用`ArrayList`等集合类