要使用自定义比较器创建TreeSet,让我们首先创建一个Integer数组并将其设置为TreeSet
Integer arr[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 }; Set<Integer> set = new TreeSet<Integer>(Collections.reverseOrder());
上面,我们将Comparator与配合使用reverseOrder()
,它返回一个强加自然顺序相反的比较器。
import java.util.Collections; import java.util.Set; import java.util.TreeSet; public class Demo { public static void main(String args[]) throws Exception { Integer arr[] = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 }; Set<Integer> set = new TreeSet<Integer>(Collections.reverseOrder()); for (int i = 0, n = arr.length; i < n; i++) { set.add(arr[i]); } System.out.println("TreeSet = "+set); System.out.println(((TreeSet<Integer>) set).comparator()); } }
输出结果
TreeSet = [100, 90, 80, 70, 60, 50, 40, 30, 20, 10] java.util.Collections$ReverseComparator@6276ae34