在Java中如何将数组中的数据倒置
1.
public class Test { public static void main(String[] args) { int[] ary={10,28,9,12,38,46,59}; System.out.println(Arrays.toString(reverseA(ary))); } public static int[] reverseA(int[] arry){ int length=arry.length; int[] re=new int[length]; for(int i=0;i<length;i++){ re[length-1-i]=arry[i]; } arry=re; return arry; } }
2..在原数组上进行操作了,这时的思路是在原数组上进行元素互换,代码如下:
对称交换 效率比所有的交换效率要高
import java.util.Arrays; public class Test { public static void main(String[] args) { int[] ary={10,28,9,12,38,46,59}; System.out.println(Arrays.toString(ary)); reverseB(ary); System.out.println(Arrays.toString(ary)); } public static void reverseB(int[] arry){ for(int i=0;i<arry.length/2;i++){ int temp=arry[i]; arry[i]=arry[arry.length-1-i]; arry[arry.length-1-i]=temp; } } }
3.使用集合个工具类: Collections.reverse(ArrayList) 将数组进行反转
import java.util.Arrays; import java.util.Collections; public class Demo { public static void main(String[] args) { int[] arry={6,10,18,20,1,35,35}; System.out.println("反转前排序: " + Arrays.toString(arry)); ArrayList arrayList = new ArrayList(); for(int a:arry){ arrayList.add(a); } System.out.println(arrayList); Collections.reverseOrder(); Collections.reverse(arrayList); System.out.println("反转后的顺序是:"+arrayList); } }