可比VS&lt ;?扩展Comparable> [英] Comparable VS <? extends Comparable>

查看:76
本文介绍了可比VS&lt ;?扩展Comparable>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于以下代码:

public class Test <T extends Comparable>{
    public static void main(String[] args){
        List<String> lst = Array.asList("abc","def");
        System.out.println(func(lst));
    }
    public static boolean func(List<**here**> lst){
        return lst.get(0).compareTo(lst.get(1)) == 0;
    }
}

为什么要在此处编写?扩展了Comparable"?,而不能编写"Comparable"?

why writing " ? extends Comparable" here would compile , and writing "Comparable" would not compile?

提前谢谢.

推荐答案

之所以会发生这种情况,是因为泛型是不变.即使String Comparable,也意味着:

This happens because generics are invariant. Even if String is a Comparable, meaning:

String s = "";
Comparable c = s; // would work

这些泛型不起作用:

List<Comparable> listC = List.of();
List<String> listS = List.of();

listC = listS; // will fail

无论ComparableString之间的关系如何,这都行不通.

And this would not work no matter what is the relationship between Comparable and String.

当您将该方法的定义更改为:

When you change the definition of that method to:

public static boolean func(List<? extends Comparable> lst) {
    ...
}

这是说:具有扩展绑定的通配符使类型为协变.

这意味着:

List<? extends Comparable> listC = List.of();
List<String> listS = List.of();

listC = listS; // would work here

或更简单地说,这意味着List<String> List<? extends Comparable>的子类型.

Or in simpler words it means that List<String> is a subtype of List<? extends Comparable>.

现在要付出很小的代价,因为listC现在是元素的生产者,这意味着您可以从元素中取出元素,但不能在其中放入任何东西.

There is a small price to pay now, because listC is now a producer of elements, meaning you can take elements out of it, but you can not put anything into it.

很容易理解之后,您还没有做完,因为当这样编写时,该方法的定义是完全正确的:

And well after you understand this, you are not done yet, because the definition of that method would be entirely correct, when written like this:

 public static <T extends Comparable<? super T>> boolean func(List<T> lst) {
      .....
 }

这篇关于可比VS&lt ;?扩展Comparable&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆