Re: Revisit: List list = new ArrayList();
Knute Johnson wrote:
The JDK does not provide any direct implementations of this interface:
it provides implementations of more specific subinterfaces like Set and List.
This interface is typically used to pass collections around and manipulate them
where maximum generality is desired.
So wouldn't that suggest that Collection should be used instead of List?
Patricia Shanahan wrote:
In many case, code that creates or modifies a structure needs to know if
it is supposed to be ordered, and how it handles duplicates. Code that
only needs to process each item in its natural order is more likely to
just see it as a Collection.
The rule is, "Use the most general type *applicable*."
Not, "Use the most general type."
If a Collection doesn't support what your algorithm needs, use the more
specific type that does, but nothing more specific than that.
So in Patricia's example, if the algorithm requires an ordered collection that
tolerates duplicates, use a List. A Collection will not have access to the
behaviors that you need. If the algorithm only requires that you iterate
through the collection, use Iterable; you don't even need a Collection.
So to Knute's question - that Collection is more general than List does not
automatically require the variable to be of type Collection. It is even valid
to declare a variable to be of a specific implementing class, if the full
behavior set of that class is what you need. This is the case, for example,
with java.util.Properties - it is really never used as a Map.
--
Lew