JAVA编程问题求助 编写程序,把一个数组中的元素倒过来。例如原数组为1,2,3,4,5。则倒排

JAVA编程问题求助

编写程序,把一个数组中的元素倒过来。例如原数组为1,2,3,4,5。则倒排后的值为5,4,3,2,1。

请给我完整程序代码并稍加讲解。

import java.util.*;
import static java.lang.System.*;
import static java.util.Arrays.*;
public class Test
{
public static void main(String[] args)
{
Integer[] array={1,2,3,4,5};
//数组工具类的排列方法,我开始尝试使用Lambda表达式但是失败了
sort(array,new Comparator<Integer>()
{
public int compare(Integer a,Integer b)
{
//如果a大于b返回a小于b,反之亦然,造成倒序排列的效果
return a>b?-1:a<b?1:0;
}
});
//输出排列后的数组,输出"[5, 4, 3, 2, 1]"
out.println(Arrays.toString(array));
}
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-07-03
public static void main(String[] args) {
       int[] a = new int[]{1,2,3,4,5}; 
       int[] n = new int[a.length];
       
       int index = a.length - 1;
       for(int i = 0; i < a.length ; i++){
       n[i] = a[index];
       index--;
       }
       
       for(int i : n){
       System.out.println(i);
       }
}

第2个回答  2015-07-03
public static void main(String[] args) {
List list = new ArrayList();
list.add(1);
list.add(2);
list.add(3);
System.out.println(list.toString());
Collections.reverse(list);
System.out.println(list.toString());
}