在 java 中,初始化数组的五种方法包括:直接初始化。使用数组字面量。使用 for 循环。使用 arrays.fill() 方法。使用第三方库(例如 guava)。

Java 初始化数组的方法
在 Java 中,可以采用以下方法来初始化数组:
1. 直接初始化
<code class="java">int[] numbers = {1, 2, 3, 4, 5};
String[] names = {"Alice", "Bob", "Carol"};</code>2. 使用数组字面量
立即学习“Java免费学习笔记(深入)”;
<code class="java">int[] numbers = new int[]{1, 2, 3, 4, 5};
String[] names = new String[]{"Alice", "Bob", "Carol"};</code>注意:使用数组字面量时,元素的类型必须显式指定,如上面的 int[] 和 String[]。
3. 使用 for 循环
<code class="java">int[] numbers = new int[5];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = i + 1;
}
String[] names = new String[3];
for (int i = 0; i < names.length; i++) {
names[i] = "Name" + (i + 1);
}</code>4. 使用 Arrays.fill() 方法
<code class="java">int[] numbers = new int[5]; Arrays.fill(numbers, 0); String[] names = new String[3]; Arrays.fill(names, "Unknown");</code>
注意:Arrays.fill() 方法会用指定的元素填充整个数组。
5. 使用第三方库
一些第三方库(例如 Guava)提供了额外的初始化数组的方法,如:
<code class="java">import com.google.common.collect.ImmutableList; int[] numbers = ImmutableList.of(1, 2, 3, 4, 5).toArray();</code>










