Java Collections Interview Questions

What is Java Collections Framework

Collections are used in every programming language and initial java release contained few classes for collections: Vector, Stack, Hashtable, Array. But looking at the larger scope and usage, Java 1.2 came up with Collections Framework that group all the collections interfaces, implementations and algorithms.
Java Collections have come through a long way with usage of Generics and Concurrent Collection classes for thread-safe operations. It also includes blocking interfaces and their implementations in java concurrent package.
Some of the benefits of collections framework are;

  • Reduced development effort by using core collection classes rather than implementing our own collection classes.
  • Code quality is enhanced with the use of well tested collections framework classes.
  • Reduced effort for code maintenance by using collection classes shipped with JDK.
  • Reusability and Interoperability

What is the benefit of Generics in Collections Framework?

Java 1.5 came with Generics and all collection interfaces and implementations use it heavily. Generics allow us to provide the type of Object that a collection can contain, so if you try to add any element of other type it throws compile time error.
This avoids ClassCastException at Runtime because you will get the error at compilation. Also Generics make code clean since we don’t need to use casting and instanceof operator.

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.

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

What is the difference between ArrayList and Vector?

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.

What is the difference between ArrayList and LinkedList?

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.

What is the difference between Iterator and ListIterator?

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.

What is the difference between Iterator and Enumeration?

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.

What is the difference between List and Set?

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

What is the difference between HashSet and TreeSet?

HashSet maintains no order whereas TreeSet maintains ascending order.

What is the difference between Set and Map?

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

What is the difference between HashSet and HashMap?

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

What is the difference between HashMap and TreeMap?

HashMap maintains no order but TreeMap maintains ascending order.

What is the difference between HashMap and Hashtable?

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.

What is the difference between Collection and Collections?

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.

What is the difference between Comparable and Comparator?

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.

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.

What is difference between Array and ArrayList?

Arrays

  • Arrays can contain primitive or Objects whereas
  • Arrays are fixed size whereas
  • Arrays doesn’t provide a lot of features like ArrayList, such as addAll, removeAll, iterator etc.

ArrayList

  • ArrayList can contain only Objects.
  • ArrayList size is dynamic.
  • ArrayList provide a lot of features like ArrayList, such as addAll, removeAll, iterator etc.

Although ArrayList is the obvious choice when we work on list, there are few times when array are good to use.

If the size of list is fixed and mostly used to store and traverse them.
For list of primitive data types, although Collections use autoboxing to reduce the coding effort but still it makes them slow when working on fixed size primitive data types.

What is EnumSet?

java.util.EnumSet is Set implementation to use with enum types. All of the elements in an enum set must come from a single enum type that is specified, explicitly or implicitly, when the set is created. EnumSet is not synchronized and null elements are not allowed. It also provides some useful methods like copyOf(Collection c), of(E first, E… rest) and complementOf(EnumSet s).

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.

What is the advantage of Properties file?

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.

What does the hashCode() and equals() method?

hashCode()

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.

equals()

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.

How to synchronize List, Set and Map elements?

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){}

What is the advantage of generic collection?

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

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.

What is the Dictionary class?

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

What is the default size of load factor in hashing based collection?

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