TreeSet依靠TreeMap来实现的。TreeSet是一个有序集合,她的元素按照升序排列,
默认采用自然顺序排列(1在2之前,a在b之前),TreeSet中的对象元素需要实现Comparable接口。
如果想自定义排序算法,可以在构造函数创建对象时传入自定义的比较器。
1 package testCollection; 2 3 import java.util.Iterator; 4 import java.util.Random; 5 import java.util.TreeSet; 6 7 /** 8 * @author gejing gjblmdlm@sina.com 9 * @version 创建时间:2014年4月22日 下午11:19:13 类说明 : 10 */ 11 public class NoRepeatRandom { 12 public static void main(String[] args) { 13 TreeSet<Integer> tree_set = new TreeSet<>(); 14 Random random = new Random(); 15 int count = 0; 16 while (count < 10) { 17 //去除重复的数字 18 boolean succeed = tree_set.add(random.nextInt(100)); 19 if (succeed) { 20 count++; 21 } 22 } 23 int size = tree_set.size(); 24 Integer[] array = new Integer[size]; 25 tree_set.toArray(array); 26 System.out.println("生成的随机数组如下:"); 27 for (Integer integer : array) { 28 System.out.print(integer.toString() + " "); 29 } 30 31 System.out.println(" ++++++++++++++++++++++++++++++++++++"); 32 Iterator<Integer> iterator = tree_set.iterator(); 33 while (iterator.hasNext()) { 34 System.out.print(iterator.next() + " "); 35 } 36 37 } 38 }