-1

これは私にはかなり奇妙に見えます。誰かが説明できますか?

コードは「? 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;         
    }


}
4

1 に答える 1

1

これは、正しい型を推測できない三項演算子に関連しています。三項演算子と Collections.emptyList() の場合は、この質問 Java を確認してください。

于 2013-04-08T05:44:02.557 に答える