简体   繁体   中英

How to call a generic method?

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>)

  • First argument "A" T can be anything between Object and String
  • Second argument T can be anything between String and String since the generic argument is explicitly defined by List<String>

T is String

method("A",new List<Object>)

  • First argument "A" T can be anything between Object and String
  • Second argument T can be anything between Object and Object since the generic argument is explicitly defined by List<Object>

T is Object

method(new Object(),new List<String>)

  • First argument new Object() T can be anything between Object and Object
  • Second argument T can be anything between 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM