Is <T> List<? extends T> f() a useful signature

Viewed 2312

Is <T> List<? extends T> f() a useful signature? Is there any problem with it / using it?

This was an interview question. I know this:

  1. It compiles fine
  2. Use it like List<? extends Number> lst = obj.<Number>f(), and then I can call on lst only those List methods that do not contain T in their signatures (say, isEmpty(), size(), but not add(T), remove(T)

Does that fully answer the question?

4 Answers

This method signature is "useful", in the sense that you can implement non-trivial, non-degenerate methods with it (that is, returning null and throwing errors are not your only options). As the following example shows, such a method can be useful for implementing some algebraic structures like e.g. monoids.

First, observe that List<? extends T> is a type with the following properties:

  • You know that all elements of this list conform to the type T, so whenever you extract an element from this list, you can use it in position where a T is expected. You can read from this list.
  • The exact type is unknown, so you can never be certain that an instance of a particular subtype of T can be added to this list. That is, you effectively cannot add new elements to such a list (unless you use nulls / type casts / exploit unsoundness of Java's type system, that is).

In combination, it means that List<? extends T> is kind-of like an append-protected list, with type-level append-protection.

You can actually do meaningful computations with such "append-protected" lists. Here are a few examples:

  • You can create append-protected lists with a single element:

    public static <T> List<? extends T> pure(T t) {
      List<T> result = new LinkedList<T>();
      result.add(t);
      return result;
    }
    
  • You can create append-protected lists from ordinary lists:

    public static <T> List<? extends T> toAppendProtected(List<T> original) {
      List<T> result = new LinkedList<T>();
      result.addAll(original);
      return result;
    }
    
  • You can combine append-protected lists:

    public static <T> List<? extends T> combineAppendProtected(
      List<? extends T> a,
      List<? extends T> b
    ) {
      List<T> result = new LinkedList<T>();
      result.addAll(a);
      result.addAll(b);
      return result;
    }
    
  • And, most importantly for this question, you can implement a method that returns an empty append-protected list of given type:

    public static <T> List<? extends T> emptyAppendProtected() {
      return new LinkedList<T>();
    }
    

Together, combine and empty form an actual algebraic structure (a monoid), and methods like pure ensure that it's non-degenerate (i.e. it has more elements that just an empty list). Indeed, if you had an interface similar to the usual Monoid typeclass:

  public static interface Monoid<X> {
    X empty();
    X combine(X a, X b);
  }

then you could use the above methods to implement it as follows:

  public static <T> Monoid<List<? extends T>> appendProtectedListsMonoid() {
    return new Monoid<List<? extends T>>() {
      public List<? extends T> empty() {
        return ReadOnlyLists.<T>emptyAppendProtected();
      }

      public List<? extends T> combine(
        List<? extends T> a,
        List<? extends T> b
      ) {
        return combineAppendProtected(a, b);
      }
    };
  }

This shows that methods with the signature given in your question can be used to implement some common design patterns / algebraic structures (monoids). Admittedly, the example is somewhat contrived, you probably wouldn't want to use it in practice, because you don't want to astonish the users of your API too much.


Full compilable example:

import java.util.*;

class AppendProtectedLists {

  public static <T> List<? extends T> emptyAppendProtected() {
    return new LinkedList<T>();
  }

  public static <T> List<? extends T> combineAppendProtected(
    List<? extends T> a,
    List<? extends T> b
  ) {
    List<T> result = new LinkedList<T>();
    result.addAll(a);
    result.addAll(b);
    return result;
  }

  public static <T> List<? extends T> toAppendProtected(List<T> original) {
    List<T> result = new LinkedList<T>();
    result.addAll(original);
    return result;
  }

  public static <T> List<? extends T> pure(T t) {
    List<T> result = new LinkedList<T>();
    result.add(t);
    return result;
  }

  public static interface Monoid<X> {
    X empty();
    X combine(X a, X b);
  }

  public static <T> Monoid<List<? extends T>> appendProtectedListsMonoid() {
    return new Monoid<List<? extends T>>() {
      public List<? extends T> empty() {
        return AppendProtectedLists.<T>emptyAppendProtected();
      }

      public List<? extends T> combine(
        List<? extends T> a,
        List<? extends T> b
      ) {
        return combineAppendProtected(a, b);
      }
    };
  }

  public static void main(String[] args) {
    Monoid<List<? extends String>> monoid = appendProtectedListsMonoid();
    List<? extends String> e = monoid.empty();
    // e.add("hi"); // refuses to compile, which is good: write protection!
    List<? extends String> a = pure("a");
    List<? extends String> b = pure("b");
    List<? extends String> c = monoid.combine(e, monoid.combine(a, b));
    System.out.println(c); // output: [a, b]
  }

}

I interpret "is it a useful signature" to mean "can you think of a use-case for it".

T is determined at the call site, not inside the method, so there are only two things that you can return from the method: null or an empty list.

Given that you can create both of these values in roughly as much code as invoking this method, there isn't really a good reason to use it.


Actually, another value that can be safely returned is a list where all of the elements are null. But this isn't useful either, since you can only invoke methods which add or remove literal null from the return value, because of the ? extends in the type bound. So all you've got is thing which counts the number of nulls it contains. Which isn't useful either.

The official Generics tutorial suggests not to use wildcard return types.

These guidelines do not apply to a method's return type. Using a wildcard as a return type should be avoided because it forces programmers using the code to deal with wildcards."

The reasoning given isn't exactly convincing, though.

It's not particularly useful, for the reasons given in other answers. However, consider it's "usefulness" in a class like the following (although it's probably a bit of an antipattern):

public class Repository {
    private List<Object> lst = new ArrayList<>();

    public <T> void add(T item) {
        lst.add(item);
    }

    @SuppressWarnings("unchecked")
    public <T> List<? extends T> f() {
        return (List<? extends T>) lst;
    }

    public static void main(String[] args) {
        Repository rep = new Repository();
        rep.add(BigInteger.ONE);
        rep.add(Double.valueOf(2.0));
        List<? extends Number> list = rep.f();
        System.out.println(list.get(0).doubleValue() + list.get(1).doubleValue());
    }
}

Note the following features:

  1. The declared return type of f() means that the caller can set whatever T they like and the method will return the required type. If f() weren't declared like that, then the caller would need to cast every call to get(N) to the required type.
  2. As it uses a wildcard, the declared return type makes the returned list read-only. This can often be a useful feature. When caller a getter, you don't want it to return a list you can write to. Often, getters use Collections.unmodifiableList() which forces a list to be read-only at run-time, but using the wildcard generic parameter forces the list to be read-only at compile-time!
  3. The drawback is that it's not particularly type-safe. It is up to the caller to ensure that f() returns a type where T is a common superclass of all the previously added items.
  4. It would typically be much better to make the class Repository generic instead of the method f().
Related