为什么是List< String> List的子类型,但不是List< Object&gt ;? [英] Why is List<String> a subtype of List, but not of List<Object>?

查看:250
本文介绍了为什么是List< String> List的子类型,但不是List< Object&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:

为什么List< Number>而不是子类型的List< Object> ;?


不是 String Java中的 Object 的子类型



然后,我如何将 List< String> 类型的对象转换为接受 List< Object> 作为参数?但我可以将这样的对象传递给一个接受 List 作为参数的函数。

解决方案


是的,它不是String的子类型吗?是,但不会使 List< String> List< Object> 的子类型。



考虑下面的例子:

  List< String> l1 = new ArrayList< String>(); 
列表< Object> l2 = l1; //这是真实Java中的编译错误
l2.add(new Integer(42));
String oops = l1.get(0);如果(假设) List< String>

>

List< Object> 的子类型,那么你最终将一个整数分配给一个最后一条语句中的字符串变量。简而言之,我们会破坏静态类型的安全性。







我可以这样一个对象转换为一个接受List作为参数的函数。

是的,那是真的。但是,您正在处理原始类型,并且在将对象从列表中拉出时必须使用显式类型转换。例如,上述内容需要重写如下:

  List< String> l1 = new ArrayList< String>(); 
列表l2 = l1;
l2.add(new Integer(42));
String oops =(String)l1.get(0);

请注意,类型转换意味着我们必须用运行时类型替换静态类型安全 - 安全。 (当然,在这种情况下,类型转换将在运行时失败,因为实例的类型是错误的。)


Possible Duplicate:
Why is List<Number> not a sub-type of List<Object>?

Isn't String a subtype of Object in Java?

Then, how come I cannot pass an object of type List<String> into a function that accepts List<Object> as a parameter? I can, though, pass such an object into a function that accepts List as a parameter.

解决方案

Isn't String a subtype of Object in Java?

Yes it is, but that doesn't make List<String> a subtype of List<Object>.

Consider this example:

    List<String> l1 = new ArrayList<String>();
    List<Object> l2 = l1;  // This is a compilation error in real Java
    l2.add(new Integer(42));
    String oops = l1.get(0);

If (hypothetically) List<String> was subtype of List<Object>, then you'd end up assigning a Integer to a String variable in the last statement. In short, we would have broken static type safety.


I can, though, pass such an object into a function that accepts List as a parameter.

Yes, that is true. But then you are dealing with raw types and you have to use explicit type casts when pulling objects out of the list. For example, the above would need to be rewritten as follows:

    List<String> l1 = new ArrayList<String>();
    List l2 = l1;
    l2.add(new Integer(42));
    String oops = (String) l1.get(0);

Note that the type-cast means we've had to replace static type-safety with runtime type-safety. (And, of course, in this case the typecast will fail at runtime because the instance has the wrong type.)

这篇关于为什么是List&lt; String&gt; List的子类型,但不是List&lt; Object&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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