Friday, 12 July 2013

Difference between Set, List and Map in #Java #interview

Set (Interface)

  • Set is an un-ordered collection which doesn’t allows duplicate (no-duplicate) elements
  • We can iterate the values by calling iterator() method

Set s = new HashSet();
Iterator iter = s.iterator();

List (Interface)

  • List is an ordered collection which allows duplicate elements
  • We can iterate the values by calling iterator() method

List li = new ArrayList();
Iterator iter = li.iterator();


Map (Interface)

  • In Map we used to store the data in key and value pairs, we may have duplicate values but no duplicate keys
  • In Map we don’t have iterator() method, but we can get the keys by calling the method keySet()

Map m; // insert values
Set s = m.keySet();
// Get Map keys into the Set and then iterate this Set object normally
// m.keySet() returns Set object with Map keys
Iterator iter = s.iterator();

 When to use List, Set and Map in Java


  1. If you need to access elements frequently by using index, than List is a way to go. Its implementation e.g. ArrayList provides faster access if you know index.
  2. If you want to store elements and want them to maintain an order on which they are inserted into collection then go for List again, as List is an ordered collection and maintain insertion order.
  3. If you want to create collection of unique elements and don't want any duplicate than choose any Set implementation e.g.HashSet, LinkedHashSet or TreeSet. All Set implementation follow there general contract e.g. uniqueness but also add addition feature e.g. TreeSet is a SortedSet and elements stored on TreeSet can be sorted by using Comparator or Comparable in Java. LinkedHashSet also maintains insertion order.
  4. If you store data in form of key and value than Map is the way to go. You can choose from Hashtable, HashMap, TreeMap based upon your subsequent need. In order to choose between first two see difference between HashSet and HashMap in Java.

References

  •  http://java67.blogspot.com/2013/01/difference-between-set-list-and-map-in-java.html
  •  http://www.java4s.com/core-java/difference-between-java-set-list-and-map-collections/

No comments:

Post a Comment