基本思路:数组调用Arrays.sort(T[] a,Comparator<? super T> c),对Comparator进行重写。运用Random类 ,实现对数字的随机排序。
- 对数字进行随机排序。
代码如下:
import java.util.Arrays;
import java.util.Comparator;
import java.util.Random;public class RandomSort {public static void main(String[] args) {//定义数组Integer []arr = {0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8, 9};//定义随机树数Random r = new Random();//随机排序Arrays.sort(arr , new Comparator<Integer>() {@Overridepublic int compare(Integer o1, Integer o2) {//随机比较大小,随机生成0或1Integer flag = r.nextInt(2);if(flag == 0)return -1;else return 1;}});//输出for(Integer ar : arr)System.out.print(ar + " ");}}
输出结果:
2.对容器随机排序:
代码如下:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Random;public class RandomSort {public static void main(String[] args) {//定义容器List<Integer> arr = new ArrayList<Integer>();//定义随机树数Random r = new Random();//添加元素for(int i = 0 ; i < 10 ; i ++)arr.add(i);//随机排序Collections.sort(arr , new Comparator<Integer>() {@Overridepublic int compare(Integer o1, Integer o2) {//随机比较大小,随机生成0或1Integer flag = r.nextInt(2);if(flag == 0)return -1;else return 1;}});//输出Iterator<Integer> iter = arr.iterator();while(iter.hasNext()){System.out.print(iter.next() + " ");}}}
输出结果:
3.对类进行排序:
代码如下:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Random;//实现Comparable接口
class Number implements Comparable<Number>
{private int a;public Number(int a ){this.a = a;}public int GetA(){return this.a;}@Overridepublic int compareTo(Number o) {Random r = new Random();Integer flag = r.nextInt(2);if(flag == 0)return -1;else return 1;}
}
public class RandomSort {public static void main(String[] args) {//定义容器List<Number> arr = new ArrayList<Number>();//添加数组{0 , 1 , 2 , 3 , 4 , , 5 , 6 , 7 , 8 , 9}for(int i = 0 ; i < 10 ; i ++)arr.add(new Number(i));//随机排序Collections.sort(arr );//输出Iterator<Number> iter = arr.iterator();while(iter.hasNext()){System.out.print(iter.next().GetA() + " ");}}}
输出结果: