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

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

问题描述

考虑下面的方法 doSomething(List),它接受 List 作为参数.

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

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

现在考虑下面尝试调用 doSomething() 的代码片段,我尝试将 List 传递给 doSomething()

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

我的问题是为什么List不能传递给接受List的方法?

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

推荐答案

Java 中的这个通用问题可能会让任何不太熟悉泛型的人感到困惑,因为乍一看它看起来 String is object 所以 List<String> 可用于需要 List 的地方,但事实并非如此.它会导致编译错误.

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.

如果你更进一步,这确实有意义,因为List 可以存储任何东西,包括StringInteger 等,但 List 只能存储 Strings.

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.

另请看:为什么不从 List 继承?

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

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