【问题标题】:What is wrong here [duplicate]这里有什么问题[重复]
【发布时间】:2013-04-09 17:28:35
【问题描述】:

这对我来说看起来很奇怪。谁能解释一下?

注意,代码从不使用“?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;         
    }


}

【问题讨论】:

  • 这不是重复。见下面的cmets
  • 这个问题通常发生在泛型上,所以只需使用第二个编译选项(并且可能有效)

标签: java templates


【解决方案1】:

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

【讨论】:

  • 这应该是使用重复链接的评论。
  • 我知道这一点,但看起来这种情况有所不同。该线程有 List 与 List。这里我们有完全相同的类型:Comparator。如果我错了,请纠正我。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-03
  • 1970-01-01
  • 2011-01-22
  • 2016-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多