Re: Revisit: List list = new ArrayList();
- From: Hendrik Maryns <gtw37bn02@xxxxxxxxxxxxxx>
- Date: Thu, 08 Nov 2007 18:22:59 +0100
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, you’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.
So generally, you’ll do:
List<Whatever> myList = new ArrayList<Whatever>();
Collection<Something> = functionReturningCollection; // note that it
might actually return a Set or List, or some custom implementation
public usefulMethod(Collection<Stuff> args) {
// I just want some Stuff instances, don’t care which ones, since I
only use the enhanced for loop
}
etc.
HTH, H.
--
Hendrik Maryns
http://tcl.sfs.uni-tuebingen.de/~hendrik/
==================
http://aouw.org
Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html
Attachment:
signature.asc
Description: OpenPGP digital signature
- References:
- Revisit: List list = new ArrayList();
- From: Knute Johnson
- Re: Revisit: List list = new ArrayList();
- From: Patricia Shanahan
- Re: Revisit: List list = new ArrayList();
- From: Knute Johnson
- Revisit: List list = new ArrayList();
- Prev by Date: Exceptions in Threads (& MVC)
- Next by Date: Re: notifying particular thread to wake up.
- Previous by thread: Re: Revisit: List list = new ArrayList();
- Next by thread: Re: Revisit: List list = new ArrayList();
- Index(es):
Relevant Pages
|