疑惑的泛型方法:
static <T> Comparator<T> reverseOrder()用法:
TreeSet<String> ts = new TreeSet<String>(Collections.reverseOrder());疑惑之处:
方法是泛型的,但是在调用中,也就是红色部分,没有使用泛型,那么String类型如何传进此方法中呢?
求详细解读,并可延伸说下泛型易出错的用法,谢谢了。

解决方案 »

  1.   

    static <T> Comparator<T> reverseOrder()红色部分表示,此方法是一个独立的泛型方法,其泛型类型由传入的参数类型决定。
      

  2.   

    看下API就都清楚了,首先:reverseOrder方法返回<T> Comparator<T>
     static
    <T> Comparator<T>
    reverseOrder()
              Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.
    再看下TreeSet构造方法。
    TreeSet(Collection<? extends E> c)
    Constructs a new tree set containing the elements in the specified collection, sorted according to the natural ordering of its elements.
      

  3.   

    可是这个方法是无参方法啊 ,所以才比较疑惑。这里它代表的应该是反转String类型的自然排序,可是String类型没有体现啊,从哪里传进去的呢?
      

  4.   


    reverseOrder()返回的是一个比较器,然后TreeSet使用的构造方法应该是指定比较器的,和这个传入集合的构造方法不同吧。现在我主要不太明白在reverseOrder()没有返回比较器之前,它内部是如何知道自己所使用的泛型为String类型,通过什么方式传进去的呢?
      

  5.   

    TreeSet的构造函数指定了比较器的类型参数是TreeSet类型参数或其超类,此处使用了类型推断特性http://www.ibm.com/developerworks/cn/java/j-djc02113/ 推断出实际类型是String
     public TreeSet(Comparator<? super E> comparator) {
    this(new TreeMap<E,Object>(comparator));
        }