有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java这里怎么了

我觉得这很奇怪。有人能解释吗

请注意,该代码从不使用“extends”,只使用“super E”,而是出于某种特殊原因 提出了“扩展”

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) 个答案