如何在 Java 中声明和初始化数组?
您可以使用数组声明或数组文字(但仅当您立即声明并影响变量时,数组文字不能用于重新分配数组)。
对于原始类型:
int[] myIntArray = new int[3]; int[] myIntArray = {1, 2, 3}; int[] myIntArray = new int[]{1, 2, 3}; // Since Java 8. Doc of IntStream: https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html int [] myIntArray = IntStream.range(0, 100).toArray(); // From 0 to 99 int [] myIntArray = IntStream.rangeClosed(0, 100).toArray(); // From 0 to 100 int [] myIntArray = IntStream.of(12,25,36,85,28,96,47).toArray(); // The order is preserved. int [] myIntArray = IntStream.of(12,25,36,85,28,96,47).sorted().toArray(); // Sort
例如,对于类,String它是相同的:
String
String[] myStringArray = new String[3]; String[] myStringArray = {"a", "b", "c"}; String[] myStringArray = new String[]{"a", "b", "c"};
当您先声明一个数组然后对其进行初始化、将数组作为函数参数传递或返回一个数组时,第三种初始化方式很有用。显式类型是必需的。
String[] myStringArray; myStringArray = new String[]{"a", "b", "c"};