分配 Java 二维数组元素的三种方法:使用两个 for 循环;使用数组初始化器;使用 Stream API。

如何给 Java 中的二维数组分配元素
方法:
1. 使用两个 for 循环
<code class="java">int[][] array = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
array[i][j] = value;
}
}</code>2. 使用数组初始化器
立即学习“Java免费学习笔记(深入)”;
<code class="java">int[][] array = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};</code>3. 使用 Stream API
<code class="java">int[][] array = IntStream.range(0, rows)
.mapToObj(i -> IntStream.range(0, cols).toArray())
.toArray(int[][]::new);</code>示例:
给一个 3x3 的二维数组分配元素:
<code class="java">int[][] array = new int[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
array[i][j] = i * 3 + j;
}
}</code>输出数组:
<code>[[0, 1, 2], [3, 4, 5], [6, 7, 8]]</code>
以上就是java怎么给二维数组分配元素的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号