【问题标题】:What flexibility does the wild card type give in the type parameter ?通配符类型在类型参数中提供什么灵活性?
【发布时间】:2013-02-21 15:27:22
【问题描述】:

考虑静态实用程序中的通用min 方法,该方法旨在返回集合中的最小元素。为什么我们需要将其声明为

 public static <T extends Comparable<? super T>> T min(Set<? extends T> producerSet)

如果我们改为将其声明为

会有什么问题
public static <T extends Comparable<T>> T min(Set<? extends T> producerSet)

type 参数中的通配符类型在这里给了我什么灵活性?

【问题讨论】:

  • 路过评论:这可能在 Angelika Langer 的泛型常见问题解答中的某个地方,因为一切都是。 (当涉及到泛型问题时,文档是必读的。)
  • 见鬼,它在泛型教程中:docs.oracle.com/javase/tutorial/extra/generics/morefun.html - 例如,如果你有 Animal implements Comparable&lt;Animal&gt; 和 Cat extends Animal 类,如果你没有使用 ? super T 那么你可以'不要在 List&lt;Cat&gt; 上调用 min(),因为它要求项目类型与自身完全可比,而您只需要它与自身或超类型可比。

标签: java generics


【解决方案1】:

这涵盖了 T 是 Comparable 实现者的子类的情况。考虑以下几点:

public static class A implements Comparable<A> {

   public int compareTo(A o) {
      return 0;
   }
}
public static class B extends A {}

public static <T extends Comparable<T>> T min(Set<? extends T> producerSet) {
   return null;
}

public static void main(String[] args) {
   Set<B> set = new HashSet<B>();
   min(set); // incompatible with method signature
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-16
    相关资源
    最近更新 更多