在Java中,数组的定义和赋值可以通过以下几种方式进行:
dataType[] arrayName = new dataType[arraySize];
例如:
int[] numbers = new int[5];
dataType[] arrayName = {value1, value2, value3, ...};
例如:
int[] numbers = {1, 2, 3, 4, 5};
首先声明数组,然后为每个元素赋值:
dataType[] arrayName;
arrayName = new dataType[arraySize];
arrayName[0] = value1;
arrayName[1] = value2;
...
例如:
int[] numbers;
numbers = new int[5];
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
numbers[3] = 4;
numbers[4] = 5;
dataType[] arrayName = new dataType[arraySize];
for (int i = 0; i < arraySize; i++) {
arrayName[i] = someValue;
}
例如:
int[] numbers = new int[5];
for (int i = 0; i < 5; i++) {
numbers[i] = i + 1;
}