Collections Interview Questions Part I

What is difference between fail-fast and fail-safe?

Fail-safe iterators are just opposite to fail-fast.

They never fail if you modify the underlying collection on which they are iterating, because they work on clone of Collection instead of original collection and that’s why they are called as fail-safe iterator.

Iterator of CopyOnWriteArrayList is an example of fail-safe Iterator also iterator written by ConcurrentHashMap keySet is also fail-safe iterator and never throw ConcurrentModificationException.

Can we use any class as Map key?
  • We can use any class as Map Key, however following points should be considered before using them.

  • If the class overrides equals() method, it should also override hashCode() method. The class should follow the rules associated with equals() and hashCode() for all instances.

  • If a class field is not used in equals(), you should not use it in hashCode() method. Best practice for user defined key class is to make it immutable, so that hashCode() value can be cached for fast performance.

  • Also immutable classes make sure that hashCode() and equals() will not change in future that will solve any issue with mutability.

  • For example, let’s say I have a class MyKey that I am using for HashMap key.
    MyKey name argument passed is used for equals() and hashCode()

This is the reason why String and Integer are mostly used as HashMap keys.

What are the differences between Queue and Stack in java?
  • A collection designed for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, extraction, and inspection operations.

  • Queues typically, but do not necessarily, order elements in a FIFO (first-in-first-out) manner.

  • Stack is also a form of Queue but one difference, it is LIFO (last-in-first-out). Whatever the ordering used, the head of the queue is that element which would be removed by a call to remove() or poll(). Also note that Stack and Vector are both synchronized.

Usage:

  • Use a queue if you want to process a stream of incoming items in the order that they are received. Good for work lists and handling requests.

  • Use a stack if you want to push and pop from the top of the stack only. Good for recursive algorithms.

Learn more in our Video Tutorial Section

How can we make HashMap synchronized?

HashMap can be synchronized by:

What is NavigableMap in Java ? What are its benefits over Map?
  • NavigableMap Map was added in Java 1.6, it adds navigation capability to Map data structure. It provides methods like lowerKey() to get keys which is less than specified key, floorKey() to return keys which is less than or equal to specified key, ceilingKey() to get keys which is greater than or equal to specified key and higherKey() to return keys which is greater specified key from a Map.

  • It also provide similar methods to get entries e.g. lowerEntry(), floorEntry(), ceilingEntry() and higherEntry().

  • Apart from navigation methods, it also provides utilities to create sub-Map e.g. creating a Map from entries of an exsiting Map like tailMap, headMap and subMap. headMap() method returns a NavigableMap whose keys are less than specified, tailMap() returns a NavigableMap whose keys are greater than the specified and subMap() gives a NavigableMap between a range, specified by toKey to fromKey.

What is the Difference between the Iterator and ListIterator?
  • Iterator : Iterator Can Only get Data From forward Direction.

  • ListIterator : An iterator for lists that allows one to traverse the list in either direction, modify the list during iteration, and obtain the iterator’s current position in the list.

    A ListIterator has no current element. its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next(). In a list of length n, there are n+1 valid index values, from 0 to n, inclusive.

Difference between Vector and ArrayList?

Vector & ArrayList both classes are implemented using dynamically resizable arrays, providing fast random access and fast traversal. ArrayList and Vector class both implement the List interface.

  • Synchronization - ArrayList is not thread-safe whereas Vector is thread-safe. In Vector class each method like add(), get(int i) is surrounded with a synchronized block and thus making Vector class thread-safe.

  • Data growth - Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.

Which two method you need to implement for key Object in HashMap ?

In order to use any object as Key in HashMap, it must implement equals and hashcode method in Java.

How to make a collection read only?

Use following methods:

  • Collections.unmodifiableList(list);

  • Collections.unmodifiableSet(set);

  • Collections.unmodifiableMap(map);

These methods takes collection parameter and return a new read-only collection with same elements as in original collection.

What is BlockingQueue?

A Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.

BlockingQueue methods come in four forms: one throws an exception, the second returns a special value (either null or false, depending on the operation), the third blocks the current thread indefinitely until the operation can succeed, and the fourth blocks for only a given maximum time limit before giving up.

When do you use ConcurrentHashMap in Java?

This is another advanced level collection interview questions in Java which normally asked to check whether interviewer is familiar with optimization done on ConcurrentHashMap or not.

ConcurrentHashMap is better suited for situation where you have multiple readers and one Writer or fewer writers since Map gets locked only during write operation. If you have equal number of reader and writer than ConcurrentHashMap will perform in line of Hashtable or synchronized HashMap.

Which implementation of the List interface provides for the fastest insertion of a new element into the middle of the list?

We have three implementation of List : Vector, ArrayList, LinkedList.

ArrayList and Vector both use an array to store the elements of the list.

Which collection classes provide random access of it’s elements?

ArrayList, HashMap, TreeMap, Hashtable classes provide random access to it’s elements.

What will happen if we put a key object in a HashMap which is already there ?

This tricky Java questions is part of How HashMap works in Java, which is also a popular topic to create confusing and tricky question in Java. Well if you put the same key again than it will replace the old mapping because HashMap doesn't allow duplicate keys.

What will be the problem if you don't override hashcode() method ?

You will not be able to recover your object from hash Map if that is used as key in HashMap.

How can you suppress unchecked warning in Java ?

javac compiler for Java 5 generates unchecked warnings if you use combine raw types and generics types. You can be suppress those warnings by using @SuppressWarnings("unchecked") annotation.

What is the Properties class?

The properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used.