在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"};