大家好,又见面了,我是你们的朋友全栈君。
要求:
/** * 方法一:使用临时数组 */
@Test
public void method1(){
int[] array = new int[5];
System.out.println("【方法一】:\n数组的元素为");
for (int i=0;i<array.length;i++){
array[i] = (int) (Math.random()*100);
System.out.print(array[i]+" ");
}
System.out.println();
System.out.println("数组反转后的元素为");
//准备临时数组
int[] temp = new int[array.length];
//把原数组的内容反转后赋值给数组temp
for (int i=0;i<array.length;i++){
temp[i] = array[array.length-i-1];
}
//由于要求是对原数组array实现反转效果,所以再把temp挨个赋值给array
for (int i=0;i<temp.length;i++){
array[i] = temp[i];
System.out.print(array[i]+" ");
}
}
输出结果:
在以上代码中,也可以先把array挨个赋值给 temp ,然后再反转。即:
//准备临时数组
int[] temp = new int[array.length];
for (int i=0;i<array.length;i++){
temp[i] = array[i];
}
for (int i=0;i<temp.length;i++){
array[i] = temp[temp.length-i-1];
System.out.print(array[i]+" ");
}
效果也是一样的
首尾调换:
int[] array = new int[5];
System.out.println("【方法二】:\n数组的元素为");
for (int i=0;i<array.length;i++){
array[i] = (int) (Math.random()*100);
System.out.print(array[i]+" ");
}
System.out.println();
System.out.println("数组反转后的元素为");
int middle;
for (int i=0;i<array.length/2;i++){
middle = array[i];
array[i] = array[array.length-i-1];
array[array.length-i-1] = middle;
}
for (int item : array){
System.out.print(item+" ");
}
运行结果:
int[] array = new int[5];
System.out.println("【方法三】:\n数组的元素为");
for (int i=0;i<array.length;i++){
array[i] = (int) (Math.random()*100);
System.out.print(array[i]+" ");
}
System.out.println();
System.out.println("数组反转后的元素为");
int middle;
for (int i=0,j=array.length-1;i<j;i++,j--){
middle = array[i];
array[i] =array[j];
array[j] = middle;
}
for (int item : array){
System.out.print(item+" ");
}
运行结果:
使用reverse方法将数组进行反转:
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("A");
arrayList.add("B");
arrayList.add("C");
arrayList.add("D");
arrayList.add("E");
System.out.println("反转前排序: " + arrayList);
Collections.reverse(arrayList);
System.out.println("反转后排序: " + arrayList);
}
}
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/135841.html原文链接:https://javaforall.cn