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

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?

Are definition and meaning, is to be, along with its conjugations (is, am, are, was, were, being, been). Is definition, 3rd person singular present indicative of be. See more.

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.

Is "Is" a Verb? Is the Word Is a Verb?, Co. in Springfield, Massachusetts. The company adopted its current name in 1982. Define is. is synonyms, is pronunciation, is translation, English dictionary definition of is. v. Third person singular present indicative of be. vb a form of the

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.

outhale defined, Is definition, 3rd person singular present indicative of be. See more. Third-person singular simple present indicative form of be He is a doctor. 1999 January 8, Ken Starr, quoting Bill Clinton, Referral from Independent Counsel Kenneth W. Starr

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

Merriam-Webster, VerbEdit. is. Third-person singular simple present indicative form of be quotations ▽. He is a  29 synonyms of is from the Merriam-Webster Thesaurus, plus 60 related words, definitions, and antonyms. Find another word for is.

Is, is definition: 1. he/she/it form of be 2. he/she/it form of be 3. be, used with he/she/it​: . Learn more. Arts and media Literature. Book of Isaiah, a biblical text; Is, a novel by Joan Aiken; i"s, a manga by Masakazu Katsura; iS, a manga by Chiyo Rokuhana; Infinite Stratos, a Japanese light novel series

is, Is definition: Is is the third person singular of the present tense of → be 1 . Is is often added to | Meaning, pronunciation, translations and examples. The most powerful IS boasts its most aggressive design yet with the first-ever IS 350 Black Line Special Edition. From more striking wheels * to an Indigo Blue–accented, heated wood steering wheel, it leaves a legacy all its own.

IS, Etihad has announced that it is increasing its network of worldwide destinations to 29 cities from Wednesday, July 1. As it stands, the UAE's  Donald Trumpin veljentytär Mary Trump on kirjoittanut kirjan suvustaan, jota hän kutsuu ”häiriintyneeksi”. 20:25 Tässä ovat Niko Ranta-ahon ja Sofia Belórfin salatut WhatsApp-viestit Poliisi salasi WhatsApp-viestittelyn, mutta käräjäoikeus julkisti viestit Ilta-Sanomien pyynnöstä. 17

Comments
  • Returning a wildcard is not really useful
  • You can still call add(null) etc.
  • Using type inference you can just do List<? extends Number> lst = s.f();. Also, you can do Number number = lst.get(0); System.out.println(number);.
  • I think that what the interviewer was getting at was the fact that the return type of the method contains a wildcard. From Effective Java, 2nd Ed. "You should not return a wildcard type because it forces the users of an API to deal with wildcards." (paraphrased) Perhaps the best answer is that the return type is appropriate for use in package-private or private methods within a system, but it should not be used as part of an exported API.
  • @ArtB no, the advice of the 2nd ed still very much stands: wildcards are to increase the flexibility of parameters; they should not be used in return types.
  • Well, looking very desperately for a contrived way of making it useful, you could have called a setReturnType(Class<?> cls) method on the same object beforehand, and then f() would use that information to return a list of the required type.
  • @DodgyCodeException I suppose - but this would be the protocol anti-pattern.
  • "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." Really? Invoking .<String>empty() seems way more pleasant than invoking ((List<? extends String>) new List<String>()). How would you construct an expression of type List<? extends String> without such a method?
  • @AndreyTyukin List<? extends String> list = new ArrayList<>();. Or even just new List<String> - that's a List<? extends String>.
  • @AndyTurner That's a statement, not an expression. One would have to pollute the local scope with extra variables (like list). The simple idea of instantiating an empty append-protected list would be spread over two different lines in code. And this statement is still way longer than a simple .<String>empty(). The new List<String>() is a List<? extends String> only if it's in a context where the type inference expects a List<? extends String>. It's not so useful if you want to create an expression that guides type inference instead of relying on it.
  • Wildcard lists aren't read-only. You can remove elements, you can add null to the list, and you can use a wildcard capturing helper method to add and reorder its own elements.