Scenarios to choose the collection
Q. Which is faster to iterate LinkedHashSet or LinkedList ?
LinkedList
Q. Arrange in the order of speed - HashMap, HashTable, Collections.synchronizedMap, concurrentHashmap
HashMap is fastest, then - ConcurrentHashMap, Collections.synchronizedMap, HashTable
|
Q. Scenario : You need to insert huge amount of objects and randomly delete them one by one. Which Collection data structure is best ?
LinkedList
Choosing right collection to use
Best general purpose implementations are : ArrayList, LinkedHashMap, and LinkedHashSet (marked below as " * ")
Their overall performance is better, and you should use them unless you need a special feature like, ordering or sorting.
"Ordering" refers to the order of items returned by an Iterator.
"Sorting" refers to sorting items according to Comparable or Comparator.
Set (No duplicates)
HashSet | LinkedHashSet * | TreeSet
List (Duplicate allowed)
ArrayList * | LinkedList
Vector | Stack
Map (No duplicate keys)
HashMap | LinkedHashMap * | TreeMap
Hashtable | Properties
Principal features of special implementations
- HashMap has slightly better performance than LinkedHashMap, but its iteration order is undefined.
- HashSet has slightly better performance than LinkedHashSet, but its iteration order is undefined.
- TreeSet and TreeMap are ordered and sorted, but slow.
- LinkedList has fast adding to the start of the list, and fast deletion from the interior via iteration.
Iteration order
- HashSet - undefined
- HashMap - undefined
- LinkedHashSet - insertion order
- LinkedHashMap - insertion order of keys (by default), or 'access order'
- ArrayList - insertion order
- LinkedList - insertion order
- TreeSet - ascending order, according to Comparable / Comparator
- TreeMap - ascending order of keys, according to Comparable / Comparator
Some more
- For LinkedHashSet and LinkedHashMap, the re-insertion of an item does not affect insertion order.
- For LinkedHashMap, 'access order' is from the least recent access to the most recent access. In this context, only calls to get,put, and putAll constitute an access, and only calls to these methods affect access order.
- While being used in a Map or Set, these items must not change state (hence, it is recommended that these items be immutable objects) :
1. keys of a Map
2. items in a Set
No comments:
Post a Comment
Note: only a member of this blog may post a comment.