首先简单介绍下TreeSet和TreeMap的两种排序:
自然排序
通过comparator排序1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 private static void compareWithCpmparator () { TreeSet<String> treeSet =new TreeSet<>(); List<String> list =new ArrayList<>(); list.add("a" ); list.add("d" ); list.add("b" ); treeSet.addAll(list); Iterator<String> iterator =treeSet.iterator(); while (iterator.hasNext()){ System.out.println(iterator.next()); } Comparator<String> comparator1 = (Comparator<String>) treeSet.comparator(); if (comparator1 == null ){ System.out.println("comparator1是空" ); }else { System.out.println("comparator1不是空" ); } } public static void main (String[] args) { compareWithCpmparator(); }
运行之后的结果如下:
这段代码里面获取的comparator
是空的,Debug一遍,发现这个方法其实调用的是NavigableMap
里面的comparator
1 2 3 public Comparator<? super E> comparator() { return m.comparator(); }
查看官网上对其的介绍:1 2 3 4 Comparator<? super K> comparator() Returns the comparator used to order the keys in this map, or null if this map uses the natural ordering of its keys . Returns: the comparator used to order the keys in this map, or null if this map uses the natural ordering of its keys
在调用这个方法的时候若是自然排序,那么会返回一个null。若是通过comparator进行排序的话当前集合采用的comparator
。 查看官网对reeSet的无参构造器的解释:
/**
Constructs a new, empty tree set, sorted according to the
natural ordering of its elements. All elements inserted into
the set must implement the {@link Comparable} interface.
Furthermore, all such elements must be mutually
comparable: {@code e1.compareTo(e2)} must not throw a
{@code ClassCastException} for any elements {@code e1} and
{@code e2} in the set. If the user attempts to add an element
to the set that violates this constraint (for example, the user
attempts to add a string element to a set whose elements are
integers), the {@code add} call will throw a
{@code ClassCastException}.
在使用TreeSet的时候,插入的元素需要实现Comparable这个接口,而刚刚的元素是String,查看String的代码发现:
1 public final class String implements java .io .Serializable , Comparable <String >, CharSequence {
确实实现了,再测试一个没有实现的元素: