Java Questions 110 -120  «Prev  Next»


HashMap and TreeMap (Java Questions)

  1. What type of values does HashMap allow?

    Answer:
    The HashMap allows one null key and multiple null values in a collection.

  2. What does it mean when we say Vector and Hashtable are synchronized?

    Answer:
    Vector is the synchronized counterpart of the ArrayList.
    Hashtable is the synchronized counterpart to HashMap. This means that the key methods of the class are synchronized.
    Vector implements the List interface

  3. What are the differences between a HashMap and a Hashtable in Java?

    Answer:
    Main differences between a HashMap and a Hashtable are:
    1. Synchronization: HashMap is not a synchronized collection. If it is used in multi-thread environment, it may not provide thread safety. A Hashtable is a synchronized collection. Not more than one thread can access a Hashtable at a given moment of time. The thread that works on Hashtable acquires a lock on it and it makes other threads wait till its work is completed.
    2. Null values: A HashMap allows only one null key and any number of null values. A Hashtable does not allow null keys and null values.
    3. Ordering: A HashMap implementation by LinkedHashMap maintains the insertion order of elements. A TreeMap sorts the mappings based on the ascending order of keys. On the other hand, a Hashtable does not provide guarantee of any kind of order of elements. It does not maintain the mappings of key values in any specific order.
    4. Legacy: Hashtable was not the initial part of collction framework in Java. It has been made a collection framework member, after being retrofitted to implement the Map interface. A HashMap implements Map interface and is a part of collection framework since the beginning.
    5. Iterator: The Iterator of HashMap is a fail-fast and it throws ConcurrentModificationException if any other Thread modifies the map by inserting or removing any element except iterator's own remove() method.

  4. What is one difference between HashMap and Hashtable?

    Answer:
    A Hashtable does not let you have anything that is null.

  5. What is characteristic of the LinkedHashMap?

    Answer:
    The LinkedHashMap collection maintains insertino order ( or, optionally, access order)

  6. What is a TreeMap?

    Answer:
    A TreeMap is a sorted Map.

  7. How can a custom order be defined for TreeSet and TreeMap?

    Answer:
    By using Comparable or Comparator.

  8. What is the purpose of the Queue interface?

    Answer:
    A Queue is designed to hold a listed of tasks that need to be completed.

  9. The LinkedList class has been enhanced to implement the Queue interface.

    Answer:
    Basic Queues can be handled with a LinkedList.

  10. What is the purpose of a PriorityQueue?

    Answer:
    The purpose of a PriorityQueue is to create a priority-in, priority-out.