Java 有多种方式可以将数组从后往前输出:使用 for 循环反向遍历数组使用 Enhanced for 循环反向遍历数组使用 Stream 流反向遍历数组使用 Collections.reverse() 方法反转数组使用 ArrayUtils.reverse() 方法反转数组

Java如何将数组从后往前输出
直接使用for循环反向遍历
<code class="java">int[] arr = {1, 2, 3, 4, 5};
// 从后往前遍历数组
for (int i = arr.length - 1; i >= 0; i--) {
System.out.println(arr[i]);
}</code>使用Enhanced for循环反向遍历
<code class="java">int[] arr = {1, 2, 3, 4, 5};
// 使用Enhanced for循环反向遍历数组
for (int num : arr) {
// 通过arr.length - 1 - i来得到数组中的倒数索引
System.out.println(arr[arr.length - 1 - i]);
}</code>使用Stream流反向遍历
立即学习“Java免费学习笔记(深入)”;
<code class="java">int[] arr = {1, 2, 3, 4, 5};
// 使用Stream流反向遍历数组
Arrays.stream(arr).boxed().sorted(Comparator.reverseOrder()).forEach(System.out::println);</code>其他方法
<code class="java">int[] arr = {1, 2, 3, 4, 5};
// 使用Collections.reverse()方法反转数组
Collections.reverse(Arrays.asList(arr));
// 输出反转后的数组
System.out.println(Arrays.toString(arr));</code><code class="java">import org.apache.commons.lang3.ArrayUtils;
int[] arr = {1, 2, 3, 4, 5};
// 使用ArrayUtils.reverse()方法反转数组
ArrayUtils.reverse(arr);
// 输出反转后的数组
System.out.println(Arrays.toString(arr));</code>以上就是java怎么将数组从后往前输的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号