为什么要列出< String>作为List< Object>不可接受? [英] Why List<String> is not acceptable as List<Object>?

查看:109
本文介绍了为什么要列出< String>作为List< Object>不可接受?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑接受 List< Object> 作为参数的方法 doSomething(List< Object>) p>

  private void doSomething(List< Object> list){
//做某事
}

现在考虑下面的代码片段,它试图调用 doSomething()我尝试传递 List< String> doSomething()

  List< Object>链表类; 
列表< String> StringList的;

doSomething(stringList); //编译错误不兼容的类型
doSomething(objectList); //正常工作

即使在代码下面也会抛出编译错误

  objectList = stringList; //编译错误不兼容的类型

我的问题是为什么 List< String> 不能传递给接受 List< Object>

解决方法方案

Java中的这个通用问题可能让任何对Generics不太熟悉的人感到困惑,因为它看起来像String是object,所以 List< String> ,其中 List< Object> 是必需的,但这不是真的。这会导致编译错误。

如果你再往前走一步,因为 List< Object> 可以存储任何东西包括字符串整数等,但列表< String> 只能存储字符串



另请参见:为什么不能继承列表< T> ;?


Consider below method doSomething(List<Object>) which accepts List<Object> as parameter.

private void doSomething(List<Object> list) {
    // do something
}

Now consider below code snippet which tries to call doSomething() where I try to pass List<String> to doSomething()

List<Object> objectList;
List<String> stringList;

doSomething(stringList); // compilation error incompatible types
doSomething(objectList); // works fine 

Even below code throws compilation error

objectList = stringList;  // compilation error incompatible types

My question is why List<String> can not be passed to a method which accepts List<Object>?

解决方案

This generic question in Java may look confusing to any one who is not very familiar with Generics as in first glance it looks like String is object so List<String> can be used where List<Object> is required but this is not true. It will result in compilation error.

It does make sense if you go one step further because List<Object> can store anything including String, Integer etc but List<String> can only store Strings.

Also have a look at: Why not inherit from List<T>?

这篇关于为什么要列出&lt; String&gt;作为List&lt; Object&gt;不可接受?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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