Java通用捕获和可比较

Gio*_*hal 4 java generics

这是一个容器的实现,可以与具有兼容键的任何其他容器进行比较.我在Java中使用泛型有一个奇怪的错误,任何想法?

    private static class Container
    <Key extends Comparable<? super Key>, Value>
    implements Comparable<Container<? super Key, ?>> 
    {
        public Key key;
        public Value value;
        public Container(Key k, Value v) {
            key = k;
            value = v;
        }
        public int compareTo(Container<? super Key, ?> o) {
            return key.compareTo(o.key);
        }
    }
    ...
Run Code Online (Sandbox Code Playgroud)

这是错误:

    compareTo(capture#98 of ? super Key) in
    java.lang.Comparable<capture#98 of ? super Key> cannot be applied to 
    (java.lang.Comparable<? super capture#822 of ? super Key>)
            return key.compareTo(o.key);
                      ^
    1 error
Run Code Online (Sandbox Code Playgroud)

ILM*_*tan 5

PECS:制作人延伸,消费者超级.

让我们从compareTo方法向后工作.您想要与容器进行比较,并且希望使用键进行比较(因此key.compareTo(o.key)).这意味着你o必须生产一个Key,你key必须消费一个Key.第一部分意味着您的方法声明应该是public int compareTo(Container<? extends Key, ?> o),这意味着您应该实现Comparable<Container<? extends Key, ?>>.第二部分意味着你Key应该是一个Comparable<? super Key>,这就是你拥有它的方式.

private static class Container<Key extends Comparable<? super Key>, Value>
                    implements Comparable<Container<? extends Key, ?>> {

    public Key key;
    public Value value;

    public Container(Key k, Value v) {
        key = k;
        value = v;
    }

    public int compareTo(Container<? extends Key, ?> o) {
        return key.compareTo(o.key);
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:完全按照以下评论,声明如下.注意调用compareTo的键中的翻转,以及Key根本不再需要实现Comparable.你只需要一个Container可以产生一些可以消耗的密钥Key

private static class Container<Key, Value> implements
        Comparable<Container<? extends Comparable<? super Key>, ?>> {

    //fields and constructors...

    public int compareTo(Container<? extends Comparable<? super Key>, ?> o) {
        return -o.key.compareTo(key);
    }
}
Run Code Online (Sandbox Code Playgroud)