Collection Interview Question
  1. What is the Java Collection?

    A collection (also called as container) is an object that groups multiple elements into a single unit.

  2. What are the basic interfaces of Java Collections Framework?

    Collection is the root of the collection hierarchy. A collection represents a group of objects known as its elements. The Java platform doesn’t provide any direct implementations of this interface.

    Set is a collection that cannot contain duplicate elements. This interface models the mathematical set abstraction and is used to represent sets, such as the deck of cards.

    List is an ordered collection and can contain duplicate elements. You can access any element from it’s index. List is more like array with dynamic length.

    A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value.

    Some other interfaces are Queue, Dequeue, Iterator, SortedSet, SortedMap and ListIterator.

  3. What are differences between Array and ArrayList?

    Read our detailed article on Difference between Array and ArrayList

  4. What are differences between ArrayList and Vector?

    Read our detailed article on Difference between ArrayList and Vector

  5. Why Map interface does not extend Collection interface?

    If Map extends Collection interface, then where are the elements? Map contains key-value pairs and it provides methods to retrieve list of Keys or values as Collection but it doesn’t fit into the “group of elements” paradigm.

  6. What is an Iterator?

    Iterator interface provides methods to iterate over any Collection. We can get iterator instance from a Collection using iterator() method.

    Iterator takes the place of Enumeration in the Java Collections Framework. Iterators allow the caller to remove elements from the underlying collection during the iteration. Java Collection iterator provides a generic way for traversal through the elements of a collection and implements Iterator Design Pattern.

  7. Why there is not method like Iterator.add() to add elements to the collection?

    The semantics are unclear, given that the contract for Iterator makes no guarantees about the order of iteration. Note, however, that ListIterator does provide an add operation, as it does guarantee the order of the iteration.

  8. Why Iterator don’t have a method to get next element directly without moving the cursor?

    It can be implemented on top of current Iterator interface but since it’s use will be rare, it doesn’t make sense to include it in the interface that everyone has to implement.

  9. What is iterator fail-fast property?

    Iterator fail-fast property checks for any modification in the structure of the underlying collection everytime we try to get the next element. If there are any modifications found, it throws ConcurrentModificationException.

    All the implementations of Iterator in Collection classes are fail-fast by design except the concurrent collection classes like ConcurrentHashMap and CopyOnWriteArrayList.

  10. What is iterator fail-safe property?

    Fail Safe Iterator makes copy of the internal data structure (object array) and iterates over the copied data structure.

    Any structural modification done to the iterator affects the copied data structure. Hence original data structure remains structurally unchanged and no ConcurrentModificationException throws by the fail safe iterator.

  11. How to avoid ConcurrentModificationException while iterating a collection?

    We can use concurrent collection classes to avoid ConcurrentModificationException while iterating over a collection, for example CopyOnWriteArrayList instead of ArrayList.

  12. How to reverse the List in Collections?

    There is a built in reverse method in Collections class . reverse(List list) accepts list as parameter.

    Collections.reverse(listobject);

  13. What is the difference between poll() and remove() method of Queue interface?

    Though both poll() and remove() method from Queue is used to remove the object and returns the head of the queue, there is a subtle difference between them.

    If Queue is empty() then a call to remove() method will throw Exception, while a call to poll() method returns null. By the way, exactly which element is removed from the queue depends upon queue’s ordering policy and varies between different implementation, for example, PriorityQueue keeps the lowest element as per Comparator or Comparable at head position

  14. What is Big-O notation?

    The Big-O notation describes the performance of an algorithm in terms of number of elements in a data structure. Since Collection classes are actually data structures, we usually tend to use Big-O notation to chose the collection implementation to use based on time, memory and performance.

    Example 1: ArrayList get(index i) is a constant-time operation and doesn’t depend on the number of elements in the list. So it’s performance in Big-O notation is O(1).

    Example 2: A linear search on array or list performance is O(n) because we need to search through entire list of elements to find the element.

  15. What are advantages of iterating a collection using iterator?

    For loop does not allow updating the colection(add or remove) whereas Iterator does allow modifying the collection. Also Iterator can be used where there is no clue what type of collections will be used because all collections implement Iterator interface.

  16. What is ConcurrentHashMap?

    A ConcurrentHashMap is thread-safe implementation of Map interface. In this class put and remove method are synchronized but not get method. This class is different from Hashtable in terms of locking; it means that hashtable use object level lock but this class uses bucket level lock thus having better performance.

  17. How to create Collections ReadOnly?

    We can create collections read only by below methods:

  18. What are differences between ArrayList and LinkedList?

    Read our detailed article on Difference between ArrayList and LinkedList

  19. Which collection classes are thread-safe?

    Vector, Hashtable, Properties and Stack are synchronized classes, so they are thread-safe and can be used in multi-threaded environment.

    Java 1.5 Concurrent API included some collection classes that allows modification of collection while iteration because they work on the clone of the collection, so they are safe to use in multi-threaded environment.

  20. What is Comparable and Comparator interface?

    Java provides Comparable interface which should be implemented by any custom class if we want to use Arrays or Collections sorting methods.

    Comparable interface has compareTo(T obj) method which is used by sorting methods. We should override this method in such a way that it returns a negative integer, zero, or a positive integer if “this” object is less than, equal to, or greater than the object passed as argument. Read more at Comparable in Java with Example

    Comparator interface compare(Object o1, Object o2) method need to be implemented that takes two Object argument, it should be implemented in such a way that it returns negative int if first argument is less than the second one and returns zero if they are equal and positive int if first argument is greater than second one. Read more at Comparator in Java with Example

  21. What is the difference between Synchronized Collection and Concurrent Collection?

    Java 5 has added several new Concurrent Collection classes e.g. ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue etc, which has made Interview questions on Java Collection even trickier.

    It has synchronized copy of collection e.g. ArrayList, HashMap by using Collections.synchronizedMap() Utility function.

    One Significant difference is that Concurrent Collections has better performance than synchronized Collection because they lock only a portion of Map to achieve concurrency and synchronization.

  22. How HashMap works in Java?

    HashMap stores key-value pair in Map.Entry static nested class implementation. HashMap works on hashing algorithm and uses hashCode() and equals() method in put and get methods.

    When we call put method by passing key-value pair, HashMap uses Key hashCode() with hashing to find out the index to store the key-value pair. The Entry is stored in the LinkedList, so if there are already existing entry, it uses equals() method to check if the passed key already exists, if yes it overwrites the value else it creates a new entry and store this key-value Entry.

    When we call get method by passing Key, again it uses the hashCode() to find the index in the array and then use equals() method to find the correct Entry and return it’s value. Below image will explain these detail clearly.

    ———————————

    The other important things to know about HashMap are capacity, load factor, threshold resizing. HashMap initial default capacity is 16 and load factor is 0.75.

    Threshold is capacity multiplied by load factor and whenever we try to add an entry, if map size is greater than threshold, HashMap rehashes the contents of map into a new array with a larger capacity.

    The capacity is always power of 2, so if you know that you need to store a large number of key-value pairs, for example in caching data from database, it’s good idea to initialize the HashMap with correct capacity and load factor.

  23. What is hash-collision in Hashtable and how it is handled in Java?

    Two different keys with the same hash value is known as hash-collision. Two different entries will be kept in a single hash bucket to avoid the collision.

  24. What is BlockingQueue?

    java.util.concurrent.BlockingQueue is a Queue that supports operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element.

    BlockingQueue interface is part of java collections framework and it’s primarily used for implementing producer consumer problem. We don’t need to worry about waiting for the space to be available for producer or object to be available for consumer in BlockingQueue as it’s handled by implementation classes of BlockingQueue.

    Java provides several BlockingQueue implementations such as ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue etc.

  25. What are differences between HashMap and Hashtable?

    Read our detailed article on Difference between HashMap and Hashtable

  26. What is Java Priority Queue?

    PriorityQueue is an unbounded queue based on a priority heap and the elements are ordered in their natural order or we can provide Comparator for ordering at the time of creation.

    PriorityQueue doesn’t allow null values and we can’t add any object that doesn’t provide natural ordering or we don’t have any comparator for them for ordering. Java PriorityQueue is not thread-safe and provided O(log(n)) time for enqueing and dequeing operations.

  27. What is the difference between Iterator and Enumeration?

    The main difference between Iterator and Enumeration is that Iterator has remove() method while Enumeration doesn’t.

    Hence, using Iterator we can manipulate objects by adding and removing the objects from the collections. Enumeration behaves like a read only interface as it can only traverse the objects and fetch it .

  28. When to use ArrayList and when to use LinkedList in application?

    ArrayList has constant time search operation O(1). Hence, ArrayList is preferred when there are more get() or search operation .

    Insertion , Deletion operations take constant time O(1) for LinkedList. Hence, LinkedList is preferred when there are more insertions or deletions involved in the application.

  29. What will be the output of below program?
    null val1 val2

    Note:During a put operation, when we use a key that was already used previously to store a value, it returns the previous value associated with the key.

It's good to share...Share on FacebookTweet about this on TwitterShare on LinkedInPin on PinterestShare on Google+Email this to someone

2 Thoughts on “Java Collections Interview Questions and Answers”

Leave a Reply

Your email address will not be published. Required fields are marked *