这里有什么问题

时间:2013-04-08 05:26:59

标签: java templates

这对我来说很奇怪。有人可以解释一下吗?

注意,代码从不使用“?extends”,只使用“?super E”,但出于某些特殊原因编译 提出“?extends”。

import java.util.Comparator;

public class TestClass <E> {

    private Comparator<? super E> compNatural = new Comparator<E>() {
        @SuppressWarnings("unchecked")
        @Override
        public int compare(E lhs, E rhs) {
            return ((Comparable<E>)lhs).compareTo(rhs);
        }
    };

    private Comparator<? super E> comp; 

    public TestClass(Comparator<? super E> comp) {
        // Reports an error:
        // Type mismatch: cannot convert from Comparator<capture#10-of ? extends Object> to Comparator<? super E> 
        this.comp = (comp==null) ? compNatural : comp;

        // The following compiles OK!!!
        if (comp==null) this.comp = compNatural; else this.comp = comp;         
    }


}

1 个答案:

答案 0 :(得分:1)

这涉及三元运算符无法推断出正确的类型。请检查此问题Java if ternary operator and Collections.emptyList()