0

Possible Duplicate:
What is a difference between <? super E> and <? extends E>?

Some Java programmers on a team I'm on are writing functions that return objects of type List<? extends T> to make read-only lists and return objects of type List<? super T> to make write-only lists.

In Java, what makes List<? extends T> read-only and List<? super T> write-only?

0

3 Answers 3

1

please read up on "producer extends, consumer super" (PECS) - I may need to do the same :)

Read only:

In case you would like to ensure that a method takes as a parameter a collection of items ( using generics) - when you use List<? extends T> - the list can contain any subtype of T but cannot add to the collection since it does not know at runtime the specific type of T that the List contains.

Write only:

For List<? super T>, the list can contain T regardless of the actual parameterized type (using super will allow that to happen).

Hope it helps.

0

You can get a T from a List<? extends T>, but the only thing you can put into it is a null literal. You can put a T into a List<? super T>, but the only thing you can get from it is an Object (which is then unsafe to cast down to T).

So, the restrictions make these pretty good, though imperfect, reminders of the intention. With a List<? extends T>, you can't put most things into it -- so it's kinda read-only. And with a List<? super T>, you can't get things out of it very usefully -- so it's kinda write-only.

Note that neither one of these is actually read- or write-only. I noted some of the ways you can get things into or out of them above, and with the "read-only" construct, you can still call remove functions, either on the object itself or on its iterator.

0

The definition List<? extends T> means "a List<X> implementation, where X must be T or a subclass/implementation thereof. In other words, your only guarantee is that objects already stored in the list will fit in a variable of type T. However, since the list may have been declared for a class extending or implementing T, you have no guarantee that objects of type T itself will fit into the list.

Simple example: List<String> is a List<? extends T> if T is Object. You can safely draw Object-type objects from it, but you can obviously not put other Object-type objects in it, unless they are definitely strings.

Not the answer you're looking for? Browse other questions tagged or ask your own question.