Friday 24 May 2013

JAVA INTERVIEW QUESTIONS - Map interface


1.What is a Map ?
  • A map is an object that stores associations between keys and values (key/value pairs).
  • Given a key, you can find its value. Both keys  and  values are objects.
  • The keys must be unique, but the values may be duplicated.
  • Some maps can accept a null key and null values, others cannot.
2.What are the main Implementations of the Map interface ?
The main implementations of the List interface are as follows:

  • HashMap
  • HashTable
  • TreeMap
  • EnumMap
3.What is a TreeMap ?
TreeMap actually implements the SortedMap interface which extends the Map interface. In a TreeMap the data will be sorted in ascending order of keys according to the natural order for the key's class, or by the comparator provided at creation time. TreeMap is based on the Red-Black tree data structure.

4.How do you decide when to use HashMap and when to use TreeMap ?
For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative. Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal.

5.Difference between HashMap and Hashtable ?
HashMapHashtable
HashMap lets you have null values as well as one null key.HashTable  does not allows null values as key and value.
The iterator in the HashMap is fail-safe (If you change the map while iterating, you’ll know).The enumerator for the Hashtable is not fail-safe.
HashMap is unsynchronized.Hashtable is synchronized.
Note: Only one NULL is allowed as a key in HashMap. HashMap does not allow multiple keys to be NULL. Nevertheless, it can have multiple NULL values.

6.How does a Hashtable internally maintain the key-value pairs?
TreeMap actually implements the SortedMap interface which extends the Map interface. In a TreeMap the data will be sorted in ascending order of keys according to the natural order for the key's class, or by the comparator provided at creation time. TreeMap is based on the Red-Black tree data structure.


EmoticonEmoticon