Frequently asked Java Collections interview questions and answers

Frequently asked Java Collections interview questions and answers

Java Collections Framework is the fundamental aspect of Java programming language. A good understanding of Collections framework is required to understand and leverage many powerful features of Java. Java Collections framework is heavily used in Java programming on all types of programs including web based and desktop applications. It is one of the important topics of discussion in any Java interview. Here am listing some of the frequently asked Java Collections interview questions and answers for freshers as well as experienced Java programmers.

1. What is Java Collections Framework? What are the advantages of the Java Collections Framework?

A collection, sometimes called a container, is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data. The Java collections framework (JCF) is a set of classes and interfaces that implement commonly reusable collection data structures.

The Java Collections Framework provides the following benefits:

  • Reduces programming effort by providing useful data structures and algorithms.
  • Increases program speed and quality by providing high-performance, high-quality implementations of useful data structures and algorithms.
  • Allows inter-operability among unrelated APIs
  • Reduces effort to design, learn and to use new APIs
  • Encourages software reuse

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

Collection is at the root of the Java collection’s 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 an 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.

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.

Here is the hierarchy of collection’s interfaces.

Java collections framework

3. What is the difference between ArrayList and Vector?

ArrayListVector
ArrayList is not synchronized. Hence ArrayList is not thread-safe.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.
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. ArrayList increases its size by 50% of the array size.Vector increases its size by doubling the array size.

4. How HashMap works internally in Java?

This questions is mostly asked to experienced Java developers. Check the answer here.

5. How HashSet is internally implemented in Java?

Ans.

6. What is the difference between ArrayList and LinkedList?

ArrayListLinkedList
Resizable-array implementation of the List interface. ArrayList uses a dynamic array.Doubly-linked list implementation of the List and Deque interfaces.
Frequent insertion/removal of elements can be slower based on the index. This is because the elements have to be shifted in the array.Frequent insertion/removal of elements is faster. This is because removal only requires change in the pointer location in the two neighbor nodes (elements) of the node which is going to be removed.
Search operation is faster in ArrayList because it maintains index based system for its elements.Search operation is slower because it requires traversing through all the elements for searching an element.
Memory consumption is comparatively lowMemory consumption is high because of the additional pointers required for each element to maintain the structure.
Supports only List operationsSupports both list and queue operations like poll(), peek() etc.

Additionally they may ask which is preferred – Arraylist or Linkedlist? You can say that it depends on the requirement. If the requirement involves frequent insertion or removal then LinkedList is preferred. On the other hand if the requirement involves frequent accessing of the elements then ArrayList is preferred.

7. What is the difference between Iterator and Enumeration?

IteratorEnumeration
Iterators allow the caller to remove elements from the underlying collection.With Enumeration, you cannot remove elements.
Iterator is fail-fast. Iterator is much safer as compared to Enumeration because it always denies other threads to modify the collection object which is being iterated by it.Enumeration is not fail-fast.
Iterator is slower than Enumeration.Enumeration is twice as fast as Iterator and uses very less memory.

Also, Iterator method names have been improved to make it’s functionality clear. Iterator takes the place of Enumeration in the Java Collections Framework.

8. What is the difference between Iterator and ListIterator?

IteratorListIterator
Iterator traverses the elements in forward direction only.ListIterator traverses the elements in both directions(forward & backward).
Iterator can be used with List, Set and Queue.ListIterator can be used with List only.

Additionally, ListIterator comes with extra functionalities like adding an element, replacing an element, getting index position for previous and next elements.

9. What is the difference between HashMap and HashTable?

HashMapHastTable
HashMap is not thread-safe. Since HashMap is not synchronized, it performs better(faster) than Hashtable.Mehods in HashTable are synchronized. So it is thread-safe
Allows one null key and any number of null values.Does not permit null key and null values.
HashMap retrieval is not in order i.e. HashMap does
not guarantee that the order of the map will remain
constant over time. But LinkedHashMap provides ordered retrieval.
In case of HashTable, iteration order is unpredictable
Iterator in the HashMap is a fail-fast iteratorthe enumerator for the Hashtable is not fail-fast.

10. What do you mean by fail-fast and fail-safe property?

Iterator fail-fast property checks for any modification in the structure of the underlying collection every time we try to get the next element. If the collection is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove or add methods, the iterator will throw a ConcurrentModificationException. All the implementations of Iterator in Collection classes are fail-fast by design except the concurrent collection classes like ConcurrentHashMap and CopyOnWriteArrayList.

In the context of concurrent modification, fail-safe iterator does not throw ConcurrentModificationException.

11. What is the importance of equals() and hashCode() methods?

Ans.

12. What is Generics? Explain its use with respect to Collections.

Read about Generics.

13. What is BlockingQueue?

Ans.

14. What are the differences between Comparable and Comparator interface?

Comparable and Comparator interfaces are used to sort collection or array of objects. Comparable interface is for self-comparing i.e. the class which implements comparable interface compares one of its objects with another. On the other hand, Comparator is more flexible. The class which implements Comparator can compare two objects of another class.

ComparableComparator
This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class’s natural ordering, and the class’s compareTo method is referred to as its natural comparison method.A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order. Comparators can also be used to control the order of certain data structures (such as sorted sets or sorted maps), or to provide an ordering for collections of objects that don’t have a natural ordering.
Virtually all Java core classes that implement Comparable have natural orderings that are consistent with equals. One exception is java.math.BigDecimal, whose natural ordering equates BigDecimal objects with equal values and different precisions (such as 4.0 and 4.00).It is generally a good idea for comparators to also implement java.io.Serializable, as they may be used as ordering methods in serializable data structures (like TreeSet, TreeMap). In order for the data structure to serialize successfully, the comparator (if provided) must implement Serializable.
comparison of null arguments not allowedUnlike Comparable, a comparator may optionally permit comparison of null arguments, while maintaining the requirements for an equivalence relation.
Present in java.lang packagePresent in java.util package which very much says that Comparator should be used as an utility to sort objects which Comparable should be provided by default.
compareTo(T ob)

Compares this object with the specified object for order.

compare(T o1, T o2)

Compares its two arguments for order.

equals(Object obj)

Indicates whether some other object is “equal to” this comparator

15. How can we sort a list of Objects?

If we need to sort a list of objects, we can use Collections.sort(). It provides overloaded sort() methods for natural sorting (using Comparable) or sorting based on criteria (using Comparator). Collections internally uses Arrays sorting method.

16. How can we create a synchronized collection from given collection?

We can use Collections.synchronizedCollection(Collection c) method to get a synchronized (thread-safe) collection backed by the specified collection.

17. What is the difference between HashSet and TreeSet ?

The HashSet is Implemented using a hash table and thus, its elements are not ordered. The add, remove, and contains methods of a HashSet have constant time complexity O(1). On the other hand, a TreeSet is implemented using a tree structure. The elements in a TreeSet are sorted, and thus, the add, remove, and contains methods have time complexity of O(logn).

18. What are the difference between Set and List?

SetList
Set is an unordered collection, it doesn’t maintain any order. There are few implementations of Set which
maintains the order such as LinkedHashSet (It maintains the elements in insertion order).
List is an ordered collection i.e. it maintains the order in which elements are added
Set doesn’t allow duplicate elements.List allows duplicates
Set can have only one null value at most.List allows any number of null values.
ListIterator cannot be used to traverse a SetListIterator can be used to traverse a List in both the directions(forward and backward).
The List interface provides two methods to search for a specified object index i.e. indexOf() and lastIndexOf().No methods to search for index
The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list. Can add elements at a specified index.Not possible with Set.

19. What data structure to use for ordered map?

LinkedHashMap.

20. What data structure to use for sorted map?

TreeMap.

21. What data structure to use for sorted set?

TreeSet.

22. How to convert an array to list?

We can use the Arrays.asList() method to create list of objects from an array of objects.

Example

23. How to convert an ArrayList to array?

We can use the toArray() method defined in the List interface.

Example

24. How to reverse the list?

This question is to test your knowledge of Collections utility class. Use it’s reverse() method to reverse the list.

25. How to make a collection thread safe?

Using the below methods:

  • Collections.synchronizedCollection(list) or Collections.synchronizedList(list);
  • Collections.synchronizedSet(set);
  • Collections.synchronizedMap(map);

26. How to iterate a HashMap?

It depends on what you want from the map. If you want to iterate over both keys and values, then you can use HashMap’s entrySet() method which will return a Set. You can then iterate the set using iterator. If you just want only keys or values, you can use keySet() or values() method of HashMap.

Example

27. What do you need to do to use a custom object as a key in Collection classes like Map or Set?

If you are using any custom object in Map as key, you need to override equals() and hashCode() method, and make sure they follow their contract. On the other hand if you are storing a custom object in Sorted Collection e.g. SortedSet or SortedMap, you also need to make sure that your equals() method is consistent with compareTo() method. Not following this will break the underlying collection’s principle itself e.g. Set may allow duplicate values.

28. What are the different ways to iterate a list in Java?

There are two ways to iterate over the list in Java

  • using Iterator
  • using for-each loop

Example

That’s all about the frequently asked Java Collections interview questions and answers. If you have any doubts, post it in the comments section.

 Also see,
The following two tabs change content below.
Working as a Java developer since 2010. Passionate about programming in Java. I am a part time blogger.
One comment

Add Comment

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