方法一:
public class ArrayOutOfOrder {
public static void main(String[] args) {
int n = 10;
int[] num = new int[n];
for(int i = 0; i < n;i++) {
num[i] = i + 1;
}
Random random = new Random();
for(int i = 0 ; i < n - 1;i++) {
int index = random.nextInt(n - i - 1) + i + 1;
swap(num,i,index);
}
for(int i : num)
System.out.print(i + " ");
}
public static void swap(int[] num, int i, int j) {
int temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
方法二:
public class ArrayOutOfOrder {
public static void main(String[] args) {
int n = 10;
Integer[] num = new Integer[n];
ArrayList<Integer> list = new ArrayList<>();
for(int i = 0; i < n;i++) {
list.add(i + 1);
}
Collections.shuffle(list);
list.toArray(num);
for(int i : num)
System.out.print(i + " ");
}
}