在Java中,数组是一种特殊的对象,用于存储相同类型的多个元素。数组的声明和初始化有以下几种方式:
dataType[] arrayName;
例如:
int[] numbers;
String[] names;
new
关键字创建数组,并指定数组长度:arrayName = new dataType[arraySize];
例如:
int[] numbers = new int[5];
String[] names = new String[3];
dataType[] arrayName = {value1, value2, value3, ...};
例如:
int[] numbers = {1, 2, 3, 4, 5};
String[] names = {"Alice", "Bob", "Charlie"};
dataType[] arrayName = new dataType[]{value1, value2, value3, ...};
例如:
int[] numbers = new int[]{1, 2, 3, 4, 5};
String[] names = new String[]{"Alice", "Bob", "Charlie"};
注意:在这种情况下,可以省略new dataType[]
,只保留花括号中的值:
int[] numbers = {1, 2, 3, 4, 5};
String[] names = {"Alice", "Bob", "Charlie"};