I have a method, <T> void method(T element,Collection<T> list)
, I am able to call it as method("A",list)
, where list can be List<String>
or List<Object>
But fails if I call method(new Object(),list)
where list is List<String>
Thanks in advance.
This example shows, that your List<String>
is not List<Object>
even while String
IS-A Object
. You should use generic wildcards:
<T> void method(T element,Collection<? extends T> list)
Looking at the method <T> void method(T element,Collection<T> list)
When using a generic method an appropriate T is found. If no such T exists then a compile time exception is thrown.
method("A",new List<String>)
Object
and String
String
and String
since the generic argument is explicitly defined by List<String>
T is String
method("A",new List<Object>)
Object
and String
Object
and Object
since the generic argument is explicitly defined by List<Object>
T is Object
method(new Object(),new List<String>)
new Object()
T can be anything between Object
and Object
String
and String
since the generic argument is explicitly defined by List<String>
No T exists that simultaneously satisfies both
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.