There are four types of collections and each type includes several classes.
| Type | Classes |
|---|---|
| List | ArrayList, LinkedList, CopyOnWriteArrayList |
| Set | HashSet, TreeSet, LinkedHashSet, CopyOnWriteArraySet, ConcurrentSkipListSet |
| Map | HashMap, TreeMap, LinkedHashMap, ConcurrentHashMap, ConcurrentSkipListMap |
| Queue | LinkedList, PriorityQueue, SynchronousQueue, DelayQueue, ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue, ConcurrentLinkedQueue |
Basic approach to choosing a collection:
- Select the collection type;
- Select specific class of that type, the one with extra functionality as few as possible.
Step 1: Select collection type
| Type | Functionality | Typical uses |
|---|---|---|
| List |
| Most cases where you just need to store or iterate through a "bunch of things" and later iterate through them. |
| Set |
|
|
| Map |
| Used in cases where you need to say "for a given X, what is the Y"? It is often useful for implementing in-memory caches or indexes. For example:
|
| Queue |
|
|
Step 2: Select specific class
List
| Class | Features/implementation | When to use |
|---|---|---|
| ArrayList |
| In most cases. |
| LinkedList |
| 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. |
| CopyOnWriteArrayList |
| Where you need concurrent access and where frequency of reads far outweights frequency of modifications. |
Set
| Ordering of keys | Non-concurrent | Concurrent |
|---|---|---|
| No particular order | HashSet | — |
| Sorted | TreeSet | ConcurrentSkipListSet |
| Fixed | LinkedHashSet | CopyOnWriteArraySet |
Map
| Ordering of keys | Non-concurrent | Concurrent |
|---|---|---|
| No particular order | HashMap | ConcurrentHashMap |
| Sorted | TreeMap | ConcurrentSkipListMap |
| Fixed | LinkedHashMap | — |
Queue
| Blocking? | Other criteria | Bound | Non-bound |
|---|---|---|---|
| Blocking | None | ArrayBlockingQueue | LinkedBlockingQueue |
| Priority-based | PriorityBlockingQueue | ||
| Delayed | DelayQueue | ||
| Non-blocking | Thread-safe | ConcurrentLinkedQueue | |
| Non thread-safe | LinkedList | ||
| Non thread-safe, priority-based | PriorityQueue |
Reference:
http://www.javamex.com/tutorials/collections/how_to_choose.shtml
No comments:
Post a Comment