Top 50 Java Collections Framework Interview Questions You Must Prepare 19.Mar.2024

You should first try to find another alternative iterator which are fail-safe. For example if you are using List and you can use ListIterator. If it is legacy collection, you can use enumeration.

If above options are not possible then you can use one of three changes:

  • If you are using JDK1.5 or higher then you can use ConcurrentHashMap and CopyOnWriteArrayList classes. It is the recommended approach.
  • You can convert the list to an array and then iterate on the array.
  • You can lock the list while iterating by putting it in a synchronized block.

Please note that last two approaches will cause a performance hit.

If we use generic class, we don't need typecasting. It is typesafe and checked at compile time.

HashMap maintains no order but TreeMap maintains ascending order.

There are three Differences are there:

  • We can use Iterator to traverse Set and List and also Map type of Objects. But List Iterator can be used to traverse for List type Objects, but not for Set type of Objects.
  • By using Iterator we can retrieve the elements from Collection Object in forward direction only whereas List Iterator, which allows you to traverse in either directions using hasPrevious() and previous() methods.
  • ListIterator allows you modify the list using add() remove() methods. Using Iterator you can not add, only remove the elements.

This question is just like above to test your knowledge of Collections utility class. Use it reverse() method to reverse the list.
Collections.reverse(list);

It models the mathematical set in set theory. Set interface is like List interface but with some differences. First, it is not ordered collection.So no ordering is preserved while adding or removing elements. The main feature it does provide is “uniqueness of elements“. It does not support duplicate elements.

Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ. Two Set instances are equal if they contain the same elements.

Based on above reasons, it does not have operations based on indexes of elements like List. It only has methods which are inherited by Collection interface.

Main classes implementing Set interface are : EnumSet, HashSet, LinkedHashSet, TreeSet.

Collection is an interface whereas Collections is a class. Collection interface provides normal functionality of data structure to List, Set and Queue. But, Collections class is to sort and synchronize collection elements.

Collections and Arrays classes are special utility classes to support collection framework core classes. They provide utility functions to get read-only/ synchronized collections, sort the collection on various ways etc.

Arrays also helps array of objects to convert in collection objects. Arrays also have some functions which helps in copying or working in part of array objects.

Iterators differ from enumerations in three ways:

  • Iterators allow the caller to remove elements from the underlying collection during the iteration with its remove() method. You can not add/remove elements from a collection when using enumerator.
  • Enumeration is available in legacy classes i.e Vector/Stack etc. whereas Iterator is available in all modern collection classes.
  • Another minor difference is that Iterator has improved method names e.g. Enumeration.hasMoreElement() has become Iterator.hasNext(), Enumeration.nextElement() has become Iterator.next() etc.

There are several differences between HashMap and Hashtable in Java:

  • Hashtable is synchronized, whereas HashMap is not.
  • Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.
  • The third significant difference between HashMap vs Hashtable is that Iterator in the HashMap is a fail-fast iterator while the enumerator for the Hashtable is not.

The sole purpose of an Iterator is to enumerate through a collection. All collections contain the add() method to serve your purpose. There would be no point in adding to an Iterator because the collection may or may not be ordered. And add() method can not have same implementation for ordered and unordered collections.

You have understood fail-fast in previous question. 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.

Well, simplest wer is “there is no need to do it“. Extending an interface simply me that you are creating a subtype of interface, in other words a more specialized behavior and Collection interface is not expected to do what Cloneable and Serializable interfaces do.

Another reason is that not everybody will have a reason to have Cloneable collection because if it has very large data, then every unnecessary clone operation will consume a big memory. Beginners might use it without knowing the consequences.

Another reason is that Cloneable and Serializable are very specialized behavior and so should be implemented only when required. For example, many concrete classes in collection implement these interfaces. So if you want this feature. use these collection classes otherwise use their alternative classes.

Yes, Collections class provides methods to make List, Set or Map elements as synchronized:

  • public static List synchronizedList(List l){}
  • public static Set synchronizedSet(Set s){}
  • public static SortedSet synchronizedSortedSet(SortedSet s){}
  • public static Map synchronizedMap(Map m){}
  • public static SortedMap synchronizedSortedMap(SortedMap m){}

List can contain duplicate elements whereas Set contains only unique elements.

In java. all collection which have feature of automatic sorting, uses compare methods to ensure the correct sorting of elements. For example classes which use sorting are TreeSet, TreeMap etc.

To sort the data elements a class needs to implement Comparator or Comparable interface. That’s why all Wrapper classes like Integer,Double and String class implements Comparable interface.

Comparable helps in preserving default natural sorting, whereas Comparator helps in sorting the elements in some special required sorting pattern. The instance of comparator if passed usually as collection’s constructor argument in supporting collections.

Iterator traverses the elements in forward direction only whereas ListIterator traverses the elements in forward and backward direction.

Iterator:

  • Iterator traverses the elements in forward direction only.
  • Iterator can be used in List, Set and Queue.

ListIterator:

  • ListIterator traverses the elements in backward and forward directions both.
  • ListIterator can be used in List only.

ArrayList:

  • ArrayList is not synchronized.
  • ArrayList is not a legacy class.
  • ArrayList increases its size by 50% of the array size.

Vector:

  • Vector is synchronized.
  • Vector is a legacy class.
  • Vector increases its size by doubling the array size.

Map interface provides 3 views of key-values pairs stored in it:

  • key set view
  • value set view
  • entry set view

All the views can be navigated using iterators.

  • LinkedList store elements within a doubly-linked list data structure. ArrayList store elements within a dynamically resizing array.
  • LinkedList allows for constant-time insertions or removals, but only sequential access of elements. In other words, you can walk the list forwards or backwards, but grabbing an element in the middle takes time proportional to the size of the list. ArrayLists, on the other hand, allow random access, so you can grab any element in constant time. But adding or removing from anywhere but the end requires shifting all the latter elements over, either to make an opening or fill the gap.
  • LinkedList has more memory overhead than ArrayList because in ArrayList each index only holds actual object (data) but in case of LinkedList each node holds both data and address of next and previous node.

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.

A good wer to this interview question is “because they are incompatible“. Collection has a method add(Object o). Map can not have such method because it need key-value pair. There are other reasons also such as Map supports keySet, valueSet etc. Collection classes does not have such views.

Due to such big differences, Collection interface was not used in Map interface, and it was build in separate hierarchy.

Lets note down the differences:

  • All the methods of Vector is synchronized. But, the methods of ArrayList is not synchronized.
  • Vector is a Legacy class added in first release of JDK. ArrayList was part of JDK 1.2, when collection framework was introduced in java.
  • By default, Vector doubles the size of its array when it is re-sized internally. But, ArrayList increases by half of its size when it is re-sized.

Set contains values only whereas Map contains key and values both.

HashSet maintains no order whereas TreeSet maintains ascending order.

The Dictionary class provides the capability to store key-value pairs.

This exception is thrown on invoked methods which are not supported by actual collection type.

For example, if you make a read-only list list using “Collections.unmodifiableList(list)” and then call add() or remove() method, what should happen. It should clearly throw UnsupportedOperationException.

You must know that HashMap store key-value pairs, with one condition i.e. keys will be unique. HashSet uses Map’s this feature to ensure uniqueness of elements. In HashSet class, a map declaration is as below:

private trient HashMap<E,Object> map;
//This is added as value for each key
private static final Object PRESENT = new Object();
So when you store a element in HashSet, it stores the element as key in map and “PRESENT” object as value. (See declaration above).

public boolean add(E e)
{
return map.put(e, PRESENT)==null;
}

Perhaps most easy question. List is collection of elements where as map is collection of key-value pairs. There is actually lots of differences which originate from first statement. They have separate top level interface, separate set of generic methods, different supported methods and different views of collection.

By definition, a collection is an object that represents a group of objects. Like in set theory, a set is group of elements. Easy enough !!

Prior to JDK 1.2, JDK has some utility classes such as Vector and HashTable, but there was no concept of Collection framework. Later from JDK 1.2 onwards, JDK felt the need of having a consistent support for reusable data structures. Finally, the collections framework was designed and developed primarily by Joshua Bloch, and was introduced in JDK 1.2.

Its most noticeable advantages can be listed as:

  • Reduced programming effort due to ready to use code
  • Increased performance because of high-performance implementations of data structures and algorithms
  • Provides interoperability between unrelated APIs by establishing a common language to pass collections back and forth
  • Easy to learn APIs by learning only some top level interfaces and supported operations

The equals method is used to check whether two objects are same or not. It needs to be overridden if we want to check the objects based on property. For example, Employee is a class that has 3 data members: id, name and salary. But, we want to check the equality of employee object on the basis of salary. Then, we need to override the equals() method.

This is more of a programmatic question which is seen at beginner level. The intent is to check the knowledge of applicant in Collection utility classes. For now, lets learn that there are two utility classes in Collection framework which are mostly seen in interviews i.e. Collections and Arrays.

Collections class provides some static functions to perform specific operations on collection types. And Arrays provide utility functions to be performed on array types.

//String array
String[] words = {"ace", "boom", "crew", "dog", "eon"};
//Use Arrays utility class
List wordList = Arrays.asList(words);
//Now you can iterate over the list
Please not that this function is not specific to String class, it will return List of element of any type, of which the array is. e.g.

//String array
Integer[] nums = {1,2,3,4};
//Use Arrays utility class
List numsList = Arrays.asList(nums);

The most noticeable differences are :

  • Set is unordered collection where List is ordered collection based on zero based index.
  • List allow duplicate elements but Set does not allow duplicates.
  • List does not prevent inserting null elements (as many you like), but Set will allow only one null element.

HashSet contains only values whereas HashMap contains entry(key,value). HashSet can be iterated but HashMap need to convert into Set to be iterated

ArrayList:

  • ArrayList uses a dynamic array.
  • ArrayList is not efficient for manipulation because a lot of shifting is required.
  • ArrayList is better to store and fetch data.

LinkedList:

  • LinkedList uses doubly linked list.
  • LinkedList is efficient for manipulation.
  • LinkedList is better to manipulate data.

The default size of load factor is 0.7@The default capacity is computed as initial capacity * load factor. For example, 16 * 0.75 = @So, 12 is the default capacity of Map.

Comparable:

  • Comparable provides only one sort of sequence.
  • It provides one method named compareTo().
  • It is found in java.lang package.
  • If we implement Comparable interface, actual class is modified.

Comparator:

  • Comparator provides multiple sort of sequences.
  • It provides one method named compare().
  • it is found in java.util package.
  • Actual class is not modified.

HashMap is well known class and all of us know that. So, I will leave this part by saying that it is used to store key-value pairs and allows to perform many operations on such collection of pairs.

TreeMap is special form of HashMap. It maintains the ordering of keys which is missing in HashMap class. This ordering isby default “natural ordering”. The default ordering can be override by providing an instance of Comparator class, whose compare method will be used to maintain ordering of keys.

Please note that all keys inserted into the map must implement the Comparable interface (this is necessary to decide the ordering). Furthermore, all such keys must be mutually comparable: k1.compareTo(k2) must not throw a ClassCastException for any keys k1 and k2 in the map. If the user attempts to put a key into the map that violates this constraint (for example, the user attempts to put a string key into a map whose keys are integers), the put(Object key, Object value) call will throw a ClassCastException

Use below methods:

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

Above methods take collection as parameter and return same type of collection which are synchronized and thread safe.

A java list is a “ordered” collection of elements. This ordering is a zero based index. It does not care about duplicates. Apart from methods defined in Collection interface, it does have its own methods also which are largely to manipulate the collection based on index location of element. These methods can be grouped as search, get, iteration and range view. All above operations support index locations.

The main classes implementing List interface are: Stack, Vector, ArrayList and LinkedList. Read more about them in java documentation.

If you change the value in properties file, you don't need to recompile the java class. So, it makes the application easy to manage.

SortedSet is an interface which TreeSet implements.

Fail-fast Iterators fail as soon as they realized that structure of Collection has been changed since iteration has begun. Structural changes me adding, removing or updating any element from collection while one thread is Iterating over that collection. Fail-fast behavior is implemented by keeping a modification count and if iteration thread realizes the change in modification count it throws ConcurrentModificationException.

HashMap:

  • HashMap is not synchronized.
  • HashMap can contain one null key and multiple null values.

Hashtable:

  • Hashtable is synchronized.
  • Hashtable cannot contain any null key or null value.

Iterator:

  • Iterator can traverse legacy and non-legacy elements.
  • Iterator is fail-fast.
  • Iterator is slower than Enumeration.

Enumeration:

  • Enumeration can traverse only legacy elements.
  • Enumeration is not fail-fast.
  • Enumeration is faster than Iterator.

HashMap is collection of key-value pairs whereas HashSet is un-ordered collection of unique elements. That’s it. No need to describe further.

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

The hashCode() method returns a hash code value (an integer number). The hashCode() method returns the same integer number, if two keys (by calling equals() method) are same.

But, it is possible that two hash code numbers can have different or same keys

You can iterate over a list using following ways:

  • Iterator loop.
  • For loop.
  • For loop (Advance).
  • While loop.

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.