在 Java 中反转数组 [英] Reversing an Array in Java
本文介绍了在 Java 中反转数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个这样的数组:
If I have an array like this:
1 4 9 16 9 7 4 9 11
反转数组使其看起来像这样的最佳方法是什么:
What is the best way to reverse the array so that it looks like this:
11 9 4 7 9 16 9 4 1
我有下面的代码,但我觉得有点乏味:
I have the code below, but I feel it is a little tedious:
public int[] reverse3(int[] nums) {
return new int[] { nums[8], nums[7], nums[6], nums[5], num[4],
nums[3], nums[2], nums[1], nums[0] };
}
有没有更简单的方法?
推荐答案
Collections.reverse()
如果你把你的数字放在 的
.List
中,就可以为你完成这项工作整数
Collections.reverse()
can do that job for you if you put your numbers in a List
of Integers
.
List<Integer> list = Arrays.asList(1, 4, 9, 16, 9, 7, 4, 9, 11);
System.out.println(list);
Collections.reverse(list);
System.out.println(list);
输出:
[1, 4, 9, 16, 9, 7, 4, 9, 11]
[11, 9, 4, 7, 9, 16, 9, 4, 1]
这篇关于在 Java 中反转数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文