java代码将数组元素顺序颠倒,这个程序很简单,是想纠正自己之前的一些错误的认识:
public class SwapDemo{
public static void main(String[] args){
int [] a = new int[]{
//Math.random() a pseudorandom double greater than or equal to 0.0 and less than 1.0
(int)(Math.random() * 1000),
(int)(Math.random() * 1000),
(int)(Math.random() * 1000),
(int)(Math.random() * 1000),
(int)(Math.random() * 1000),
(int)(Math.random() * 1000),
(int)(Math.random() * 1000)
};
System.out.println(Arrays.toString(a));
swap(a);
System.out.println(Arrays.toString(a));
}
public static void swap(int a[]){
int len = a.length;
for(int i=0;i
int tmp = a[i];
a[i] = a[len-1-i];
a[len-1-i] = tmp;
}
}
}
输出结果:
[704, 372, 901, 63, 257, 679, 325]
[325, 679, 257, 63, 901, 372, 704]
1.对于Math.random() API中的解释a pseudorandom double greater than or equal to 0.0 and less than 1.0
2.for(int i=0;i
3.int len = a.length;
for(int i=0;i
这种写法会更好一些,只创建了一次a.length,在移动开发中是非常有必要的