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

  • A+
Category:Languages

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?

 


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: