What is the use of the returned list <?> In the method?

eg.

public interface CacheClient { List<?> getKeysWithExpiryCheck(); } 

Or should I go back

 List<Object> 
+4
source share
4 answers

Here is a good introduction to Java Generics. [A] and [B] explain the difference between? and object. Primarily,? indicates that the type is unknown, which is a problem if you need to add items to the list. However, if you are only reading from a list, it is normal to treat the result as an object. Although, I suggest using something like

 public interface CacheClient { List<? extends Key> getKeysWithExpiryCheck(); } 

[A] http://java.sun.com/docs/books/tutorial/extra/generics/subtype.html

[B] http://java.sun.com/docs/books/tutorial/extra/generics/wildcards.html

+3
source

If you declare your method as

 List<Object> getKeysWithExpiryCheck(); 

You can only return List<Object> instances from it, and nothing more. If you, for example, try to return List<String> , you will get a compilation error. This is because although Object is a supertype of String , List<Object> not a supertype of List<String> .

+1
source

Can type safety be ensured? Returning a list of objects means that the list can contain anything.

0
source

This basically means that the collection can contain any type. However, using it is not possible to change the collection.

 public void doSomething(Collection<?> col) { for (Object o : col) { System.out.println(o); } col.add("string"); //Compile Error here ! } 
0
source

Source: https://habr.com/ru/post/1301944/


All Articles