Basic Collection Types: Collection Type Functionality Typical Uses
Basic Collection Types: Collection Type Functionality Typical Uses
Collection
type
Functionality
List
Typical uses
Most cases where you just need to
store or iterate through a "bunch of
things" and later iterate through them.
Set
Map
Stores
an association or
mapping between
"keys" and "values"
Queue
A list is the simplest of structures. It keeps its elements in the same order in
which they are inserted and allows duplicates. There are essentially three
underlying list classes:
Class
ArrayList
Features/implementation
When to use
Allows elements to be
efficiently read by index.
LinkedList
Other
elements cannot be
efficiently accessed by
index;
CopyOnWriteArrayList
Effectively, functions as a
non-synchronized queue. In
practice, rarely used: when
you need a queue, you often
need it to be concurrent or to
provide other functionality;
other implementations are
often more useful.
Note that this gives you thread-safe access, but it's not truly concurrent in the
sense that each access to the list will lock the entire list during the access.
Remember if you do this that you must always synchronize on the list
while iterating over it (and in some cases this could be bad for concurrency).
In practice, you should think carefully whether this type of list makes much
sense. If a list is being continually altered by different threads, for example,
what value do the individual index numbers really have?
Which Java Map to use?
whether you need to maintain the keys in sorted order, in some fixed
order or whether no particular order is required;
Non-concurrent
Concurrent
No particular order
HashMap
ConcurrentHashMap
Sorted
TreeMap
ConcurrentSkipListMap
Fixed
LinkedHashMap
Non-concurrent
Concurrent
No particular order
HashSet
Sorted
TreeSet
ConcurrentSkipListSet
Fixed
LinkedHashSet
CopyOnWriteArraySet
and reads far outweight writes. Any modification of the set is expensive (since a
brand new copy is created each time), but reads are non-blocking.
1. The time taken to access a skip list structure increases by some constant amount each
time the number of elements doubles; the time to access a hash table, as
in HashMap and HashSet, is effectively constant no matter how many elements are in the
set).
See the separate section on Java queues for a list of the various queue classes
and their functionality.
As mentioned above, if you need a queue that provides no extra features such
as thread-safe access or sorting, then a simple LinkedList can be used.