这个方法意味着什么?

时间:2012-05-30 21:19:53

标签: java collections

Comparator<? super E> comparator()

此方法在Sorted Set界面中声明。

超级意味着什么?

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

5 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:3)

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

EG。你可以拥有以下内容:

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的超类型。

我希望这会有所帮助。

答案 2 :(得分:0)

来自javadoc

“返回用于对此集合中的元素进行排序的比较器,如果此集合使用其元素的自然顺序,则返回null。”

:)

答案 3 :(得分:0)

答案是在界面声明中:public interface SortedSet<E> extends Set<E> { ...

这意味着implements SortedSet应指定他们将使用的 Type 的任何类。例如

class MyClass implements SortedSet<AnotherClass>

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

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

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

正如Paul Vargas指出的那样,这将适用于AnotherClass的所有子类。

您可能缺少的另一个方面是Comparator也是一个界面: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());
        }
    });

答案 4 :(得分:0)

“超级”在这里意味着该方法不需要为E返回Comparator。它可能会为E的任何超类返回一个Comparator。所以,为了使具体,如果E是String,这个方法可以给你一个更通用的对象比较器。

泛型方法会声明自己的新泛型参数。此方法仅引用由类声明SortedSet<E>声明的泛型参数E.通用方法不太常见。它们通常是静态的,如Arrays方法

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

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

我不确定外卡参数的确切定义。 ?是外卡人物。获得像List<?>这样的通配符参数时的一般模式是,您可以从中取出对象并将它们转换为Object但不能放入任何内容。