tags:

views:

160

answers:

4

e.g.

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

Or should I return

List<Object>
+3  A: 

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

wierob
Josh Bloch in Effective Java 2nd Edition recommends to return List<Key> instead List<? extends Key> because you don't loose any benefit but don't make users to use List<? extends Key> everywhere.
Roman
You lose some benefit, say, a subclass cannot tighten the generic argument (see `ZipFile` vs `JarFile` `entries`).
Tom Hawtin - tackline
A: 

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

npinti
+1  A: 

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

Péter Török
A: 

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 !
}
Tal
You can remove elements, and in fact add them back in.
Tom Hawtin - tackline
@Tom, looks like you are correct and indeed you can remove elements from the collection.However, the example I gave is valid and you get compilation error when trying to add object to the collection.
Tal
@Tal: You gave an example of code that does not compile. That does not mean there does not exist a trick that allows you to add removed elements back in.
Tom Hawtin - tackline