Knute Johnson schreef:
Patricia Shanahan wrote:
Knute Johnson wrote:
...
And why would you not;
Collection c = new ArrayList();
ArrayList seems an unfortunate choice of implementing class, given the
code only needs the common features of Collection. ArrayList makes some
insertions and removals expensive for the sake of efficient indexed
access. Why pay that cost if you don't need indexed access?
Collection does not make it clear whether duplicates are allowed or not,
so I would usually use either List or Set instead.
Patricia
From the docs:
Collection
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?
It depends on what you want to do. If you use a data structure
somewhere, you will know whether you want to allow duplicates or not,
and whether you want random access etc.
Collection OTOH is to be used as argument to functions which do not care
about that. Browse around in the Collection API, you2"ll get a grasp of
it. E.g. addAll() takes a Collection as argument: the class on which it
is called will take care of the duplicates-or-not-issue, that does not
depend on which kind of collection is passed to the function.
sort() OTOH will take a List as argument since order is needed to be
able to talk about sorting.
it is supposed to be ordered, and how it handles duplicates. Code that
just see it as a Collection.