在 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>
以上就是java怎么初始化数组的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号