为什么要列出< String>作为List< Object>不可接受? [英] Why List<String> is not acceptable as 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,所以 如果你再往前走一步,因为 另请参见:为什么不能继承列表< T> ;? Consider below method Now consider below code snippet which tries to call Even below code throws compilation error My question is why 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 It does make sense if you go one step further because Also have a look at: Why not inherit from List<T>? 这篇关于为什么要列出< String>作为List< Object>不可接受?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! List< String> $可以使用c $ c>,其中
List< Object>
是必需的,但这不是真的。这会导致编译错误。
List< Object>
可以存储任何东西包括字符串
,整数
等,但列表< String>
只能存储字符串
。
doSomething(List<Object>)
which accepts List<Object>
as parameter.private void doSomething(List<Object> list) {
// do something
}
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
objectList = stringList; // compilation error incompatible types
List<String>
can not be passed to a method which accepts List<Object>
?List<String>
can be used where List<Object>
is required but this is not true. It will result in compilation error. List<Object>
can store anything including String
, Integer
etc but List<String>
can only store Strings
.