2012-05-30 159 views
0
Comparator<? super E> comparator() 

此方法在Sorted Set接口中声明。这种方法是什么意思?

超级意味着什么?

上述方法与通用方法和带有通配符参数的方法有什么不同。

+2

“什么是差异”? –

+1

['comparator()'](http://docs.oracle.com/javase/7/docs/api/java/util/SortedSet.html#comparator()) –

+1

它“返回用于对元素进行排序的比较器在此集合中,如果此集合使用其元素的自然顺序,则为null。“ API文档还声明“返回:用于对此集合中元素进行排序的比较器,如果此集合使用其元素的自然排序,则为null”。你问的是''gobbledegook吗? –

回答

3

这意味着比较类型可以是当前类型的超类型。

例如,你可以有以下几种:

static class A { 
} 

static class B extends A { 
} 

public static void main(String[] args) { 

    Comparator<A> comparator = new Comparator<A>() { 
     public int compare(A a1, A b2) { 
      return 0; 
     } 
    }; 

    // TreeSet.TreeSet<B>(Comparator<? super B> c) 
    SortedSet<B> set = new TreeSet<B>(comparator); 

    // Comparator<? super B> comparator() 
    set.comparator(); 
} 

在这种情况下,AB的超类型。

我希望这有帮助。

3

A SortedSet需要一些规则来确定排序。 Comparator是这些规则的实施。该接口提供了一种方法来获取对它的引用,以便您可以将其用于其他目的,例如创建使用相同排序规则的另一个集合。

0

javadoc

“返回用于如果此set使用其元素的自然顺序为了在这个集合中的元素,或空的比较。”

:)

0

这个问题的答案是在接口声明:public interface SortedSet<E> extends Set<E> { ...

这意味着任何类implementsSortedSet应指定的类型他们将与合作。例如

class MyClass implements SortedSet<AnotherClass> 

,这将产生(使用eclipse),一堆方法如

public Comparator<? super AnotherClass> comparator() 
{ 
    return null; 
} 

public boolean add(AnotherClass ac) 
{ 
    return false; 
} 

原因,这将与AnotherClass所有子类起作用保罗Vargas的指出。

您可能会遗漏的另一方面是比较器也是一个接口:public interface Comparator<T>。所以你要返回的是这个的实现。

只是为了兴趣使用Comparator接口的另一个有效方法是匿名指定为Arrays.sort(Object[] a, Comparator c)方法的一部分:

如果我们有,我们可以用这个方法来排序的年龄和名字像这样的Person类:

Person[] people = ....; 
// Sort by Age 
    Arrays.sort(people, new Comparator<Person>() 
    { 
     public int compare(Person p1, Person p2) 
     { 
      return p1.getAge().compareTo(p2.getAge()); 
     } 
    }); 


// Sort by Name 
    Arrays.sort(people, new Comparator<Person>() 
    { 
     public int compare(Person p1, Person p2) 
     { 
      return p1.getName().compareTo(p2.getName()); 
     } 
    }); 
0

“超级”在这里是指不要求该方法返回一个比较为E.它也许不是返回比较为E.因此,任何超类,使混凝土,如果E是字符串,此方法可以为您提供更一般的对象比较器。

一个通用的方法会声明一个新的泛型参数。此方法仅引用类声明SortedSet<E>声明的通用参数E.通用方法不太常见。它们通常是静态的,就像阵列方法

public static <T> List<T> asList(T...) 

这里,T只是在这个方法中声明和使用。它显示返回列表中对象的类型与vararg参数中对象的类型相同。

我不确定通配符参数的确切定义。 ?是通配符。当您获得像List<?>这样的通配符参数时的一般模式是,您可以将对象移出并投射到对象,但不能放入任何东西。