What is the use of returning List<?> in a method?


public interface CacheClient
    List<?> getKeysWithExpiryCheck();

Or should I return



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

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

Could it be to ensure type safety? Returning a List of object means that the list could hold anything.

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

    col.add("string"); //Compile Error here !

Need Your Help

XML Response time ejabberd

java android xml response ejabberd

At the moment I'm trying to develop an Android Application for Instant Messaging. I want to use ejabberd for this on an Ubuntu Server. There is just one problem.