Friday, January 17, 2014

Collections: When to use them (brief summary)

Collection is a data structure actually, an object that can hold references to other objects.

Collection Framework interfaces:

1. Lists - Lists of things (ex. Lists of students).
2. Sets - Set is a collection where all the values are unique.
3. Maps - Map is a collection that holds key/value pairs. A unique key is mapped to a specific value, where both the ‘key’ and ‘value’ in are objects.

Terminologies:
1. Ordered - You can iterate through the collection in a specific order.
2. Sorted - Collection is sorted in the natural order (alphabetical for Strings).

LISTS

Arraylist - uses arrays internally for data management.

to be used when:

  • you need a resizable-array implementation of List interface
  • you need an ordered collection
  • should be considered when there is more data retrieval that adding or deleting of elements.
Vector - also implemented on similar lines of ArrayList, but some of the methods in Vector are synchronized and Vector has more methods when compared to ArrayList.



to be used when:
  • you need an ordered collection
  • should be considered when thread safety is a concern.
LinkedList - it is a LinkedList implementation. The LinkedList class uses an inner class called Entry. 

to be used when:
  • you need an ordered collection
  • faster insertion/deletion and slower retrieval when compared to ArrayList.
MAPS

HashMap - stores elements in an array of type Entry.

to be used when:
  • you need an unsorted and unordered Map
  • you need a map that allows null key and null values
  • methods are not synchronized. thread safety is not a concern
Hashtable - is implemented in the same fashion as HashMap. 


to be used when:
  • you need an unsorted and unordered Map
  • should be considered when security is important
  • you need a map that allows null key and null values
  • methods are synchronized. thread safety is a concern
  • has more utility methods than HashMap
TreeMap 

The elements in a TreeMap are sorted by the keys. 
As with every Map, only objects can be stored as keys and values in a TreeMap.
A TreeMap allows null values.
All keys that go into the TreeMap should implement the Comparable interface.

SETS

All Set implementations use Map internally. It has the same usage with Map though take note that objects in Sets should be unique.

HashSet - uses HashMap internally.
LinkedhashSet - uses LinkedHashMap
TreeSet - uses TreeMap 

reference: COLLECTIONS – WHAT HAPPENS WITHIN -Compiled by Sharad Ballepu

No comments:

Post a Comment