e.g.
public interface CacheClient
{
List<?> getKeysWithExpiryCheck();
}
Or should I return
List<Object>
e.g.
public interface CacheClient
{
List<?> getKeysWithExpiryCheck();
}
Or should I return
List<Object>
Here is a good intro to Java Generics. [A] and [B] explain the difference between ? and Object. Basically, ? indicates that the type is unknown which is a problem if you need to add items to the list. However, if you only read from the list it is OK to treat the result as an Object. Although, I suggest to use some thing 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
Could it be to ensure type safety? Returning a List of object means that the list could hold anything.
If you declare your method as
List<Object> getKeysWithExpiryCheck();
You can only return List<Object>
instances from it, and nothing else. If you e.g. try to return List<String>
, you get a compilation error. This is because although Object
is a supertype of String
, List<Object>
is not a supertype of List<String>
.
Basically it means that the collection can hold any type. However when using it's impossible to modify the collection.
public void doSomething(Collection<?> col) {
for (Object o : col) {
System.out.println(o);
}
col.add("string"); //Compile Error here !
}