The collection framework is the most important concept in java programming. It is necessary that you should have strong knowledge of the Collection framework. Through this article, I will share the topmost interview question and answers that will definitely help you in clearing your interview with flying colors.
1). What is the collection in java? List down interfaces and classes.
- The Collection is a set framework of interfaces and classes that provides an architecture to store and manipulate the group of objects.
- Java Collections can achieve all the operations that you perform on data such as searching, sorting, insertion, manipulation, and deletion.
2). What are the advantages of the Collection framework?
| Feature | Description |
|---|---|
| Performance | The collection framework provides highly effective and efficient data structures that result in enhancing the speed and accuracy of a program. |
| Maintainability | The code developed with the collection framework is easy to maintain as it supports data consistency and interoperability within the implementation. |
| Reusability | The classes in Collection Framework can effortlessly mix with other types which results in increasing the code reusability. |
| Extensibility | The Collection Framework in Java allows the developers to customize the primitive collection types as per their requirements. |
3). Why Collection doesn't extend the Cloneable and Serializable interfaces?
- The Collection is an interface that specifies a group of objects known as elements.
- The details of how the group of elements is maintained are left up to the concrete implementations of The Collection.
- For example, some Collection implementations like List allow duplicate elements whereas other implementations like Set don't.
- Here's an explanation from Oracle's documentation.
4). Explain HashMap's internal mechanism.
- HashMap uses its static inner class Node<K, V> for storing map entries. That means each entry in hashMap is a Node. Internally HashMap uses a hashCode of the key Object and this hashCode is further used by the hash function to find the index of the bucket where the new entry can be added.
- HashMap uses multiple buckets and each bucket points to a Singly Linked List where the entries (nodes) are stored.
- Once the bucket is identified by the hash function using hashcode, then hashCode is used to check if there is already a key with the same hashCode or not in the bucket(singly linked list).
- If there already exists a key with the same hashCode, then the equals() method is used on the keys. If the equals method returns true, that means there is already a node with the same key and hence the value against that key is overwritten in the entry(node), otherwise, a new node is created and added to this Singly Linked List of that bucket.
- If there is no key with the same hashCode in the bucket found by the hash function then the new Node is added into the bucket found.
5). Why Map doesn’t extend the Collection Interface?
- Collection is a collection of objects whereas Map is a collection of key-value pairs.
- Because they are of an incompatible type. List, Set, and Queue are a collection of similar kinds of objects but just values where a Map is a collection of key and value pairs.
- List Set and Queue have added as a function that takes a value as a param to add an element whereas Map has put as a function that takes a key and a value as params to add a key-value pair.
- List, Set, and Queue provides iterate functionality over the value whereas Maps has keys to iterate over which is ultimately a Set and Values as Collection.
Difference - Java Collection Interview Questions
1). Difference between Collection and Collections
| Collection | Collections |
|---|---|
| java.util.Collection is an interface. | java.util.Collections is class. |
| It is used to represent a group of objects as a single entity. | It is used to define various utility methods for collection objects |
| It is the root interface of the Collection framework | It is a utility class |
| It is used to derive the data structures of the Collection framework. | It is used to derive the data structures of the Collection framework |
2). Difference between Array and ArrayList
| Basic | Array | ArrayList |
|---|---|---|
| Size | An array is static in size. | ArrayList is dynamic in size. |
| Resizable | An Array is a fixed-length data structure. | ArrayList is a variable-length data structure. It can be resized itself when needed. |
| Initialization | It is mandatory to provide the size of an array while initializing it directly or indirectly. | We can create an instance of ArrayList without specifying its size. Java creates ArrayList of default size. |
| Performance | It performs fast in comparison to ArrayList because of its fixed size. | ArrayList is internally backed by the array in Java. The resize operation in ArrayList slows down the performance. |
| Primitive/ Generic type | An array can store both object and primitives types. | We cannot store primitive types in ArrayList. It automatically converts primitive type to object. |
| Iterating Values | We use for loop or for each loop to iterate over an array. | We use an iterator to iterate over ArrayList. |
| Adding Elements | We can add elements in an array by using the assignment operator. | Java provides the add() method to add elements in the ArrayList. |
| Single/ Multi-Dimensional | An array can be multi-dimensional. | ArrayList is always single-dimensional. |
3). Difference between Iterable and Iterator.
| Iterable | Iterator |
|---|---|
| Iterable is an interface. | Iterator is an interface. |
| Provides one single abstract method called iterator(). | Provides two abstract methods called hasNext() and next() |
| It is a representation of a series of elements that can be traversed. | It represents the object with an iteration state. |
4). Difference between ArrayList and LinkedList
| ArrayList | LinkedList |
|---|---|
| ArrayList internally uses a dynamic array to store the elements. | LinkedList internally uses a doubly linked list to store the elements. |
| Manipulation with ArrayList is slow because it internally uses an array. If any element is removed from the array, all the bits are shifted in memory. | Manipulation with LinkedList is faster than ArrayList because it uses a doubly linked list, so no bit shifting is required in memory. |
| An ArrayList class can act as a list only because it implements List only. | LinkedList class can act as a list and queue both because it implements List and Deque interfaces. |
| ArrayList is better for storing and accessing data. | LinkedList is better for manipulating data. |
5). Difference between Comparable and Comparator.
| Comparable | Comparator |
|---|---|
| Comparable provides a single sorting sequence. In other words, we can sort the collection on the basis of a single element such as id, name, and price. | The Comparator provides multiple sorting sequences. In other words, we can sort the collection on the basis of multiple elements such as id, name, and price, etc. |
| Comparable affects the original class, i.e., the actual class is modified. | Comparator doesn't affect the original class, i.e., the actual class is not modified. |
| Comparable provides compareTo() method to sort elements. | Comparator provides compare() method to sort elements. |
| Comparable is present in java.lang package. | A Comparator is present in java. util package. |
| We can sort the list elements of Comparable type by Collections.sort(List) method. | We can sort the list elements of Comparator type by Collections.sort(List, Comparator) method. |
6). Difference between List and Set
| List | Set |
|---|---|
| The list implementation allows us to add the same or duplicate elements. | The set implementation doesn't allow us to add the same or duplicate elements. |
| The insertion order is maintained by the List. | It doesn't maintain the insertion order of elements. |
| The list allows us to add any number of null values. | The set allows us to add at least one null value in it. |
| The List implementation classes are LinkedList and ArrayList. | The Set implementation classes are TreeSet, HashSet, and LinkedHashSet. |
| We can get the element of a specified index from the list using the get() method. | We cannot find the element from the Set based on the index because it doesn't provide any get method(). |
| It is used when we want to frequently access the elements by using the index. | It is used when we want to design a collection of distinct elements. |
| The method of List interface listiterator() is used to iterate the List elements. | The iterator is used when we need to iterate the Set elements. |
7). Difference between Set and Map.
| Set | Map |
| Extends the Collection interface | Doesn’t extend the Collection interface |
| Duplicate values are not allowed | Duplicate keys are not allowed but duplicate values are |
| Only one null value can be stored | Only one null key can be stored but multiple null values are allowed |
| Doesn’t maintain any insertion order | Doesn’t maintain any insertion order |
8). Differentiate between List and Map.
| List | Map |
| Belongs to java.util package | Belongs to java.util package |
| Extends the Collection interface | Doesn’t extend the Collection interface |
| Duplicate elements are allowed | Duplicate keys are not allowed but duplicate values are |
| Multiple null values can be stored | Only one null key can be stored but multiple null values are allowed |
| Preserves the insertion order | Doesn’t maintain any insertion order |
| Stores elements based on Array Data Structure | Stores data in key-value pairs using various hashing techniques |
9). Differentiate between Stacks and Queue.
| Stacks | Queue |
| Stacks are based on the LIFO principle, i.e., the element inserted at the last, is the first element to come out of the list. | Queues are based on the FIFO principle, i.e., the element inserted at the first, is the first element to come out of the list. |
| Insertion and deletion in stacks take place only from one end of the list called the top. | Insertion and deletion in queues take place from the opposite ends of the list. The insertion takes place at the rear of the list and the deletion takes place from the front of the list. |
| Insert operation is called push operation. | Insert operation is called enqueue operation. |
| Delete operation is called pop operation. | Delete operation is called dequeue operation. |
| In stacks, we maintain only one pointer to access the list, called the top, which always points to the last element present in the list. | In queues, we maintain two pointers to access the list. The front pointer always points to the first element inserted in the list and is still present, and the rear pointer always points to the last inserted element. |
10). Differentiate between the Singly Linked List and Doubly Linked List.
| Basis of comparison | Singly-linked list | Doubly linked list |
|---|---|---|
| Definition | A single linked list is a list of nodes in which a node has two parts, the first part is the data part, and the next part is the pointer pointing to the next node in the sequence of nodes. | A doubly linked list is also a collection of nodes in which a node has three fields, the first field is the pointer containing the address of the previous node, the second is the data field, and the third is the pointer containing the address of the next node. |
| Access | The singly linked list can be traversed only in the forward direction. | The doubly linked list can be accessed in both directions. |
| List pointer | It requires only one list pointer variable, i.e., the head pointer pointing to the first node. | It requires two list pointer variables, head and last. The head pointer points to the first node, and the last pointer points to the last node of the list. |
| Memory space | It utilizes less memory space. | It utilizes more memory space. |
| Efficiency | It is less efficient as compared to a doubly-linked list. | It is more efficient. |
| Implementation | It can be implemented on the stack. | It can be implemented on the stack, heap, and binary trees. |
| Complexity | In a singly linked list, the time complexity for inserting and deleting an element from the list is O(n). | In a doubly-linked list, the time complexity for inserting and deleting an element is O(1). |
11). Differentiate between Iterator and Enumeration.
| Basis for Comparison | Iterator | Enumeration |
|---|---|---|
| Basic | Iterator is a universal cursor as it is applicable for all the collection classes. | Enumeration is not a universal cursor as it applies only to legacy classes. |
| Access | Using Iterator you can read and remove the elements in the collection. | Using Enumeration you can only read the elements in the collection. |
| Methods | public boolean hasnext();
public objects next(); public void remove(); |
public boolean hasMoreElements();
public object nextElement(); |
| Limitation | Iterator is a unidirectional forward access cursor.
Iterator can not replace any element in the collection. Iterator can not add any new element to the collection. |
Enumeration is a unidirectional forward access cursor.
Enumeration support only legacy classes. Enumeration has only read-only access to the elements in a collection. |
| Overcome | To overcome the limitations of Iterator you must opt for ListIterator. | To overcome the limitations of Enumeration you must opt for Iterator. |
12). Differentiate between HashMap and HashTable
| HashMap | Hashtable |
|---|---|
| HashMap is non-synchronized. It is not threaded safe and can't be shared between many threads without proper synchronization code. | Hashtable is synchronized. It is thread-safe and can be shared with many threads. |
| HashMap allows one null key and multiple null values. | Hashtable doesn't allow any null key or value. |
| HashMap is a new class introduced in JDK 1.2. | Hashtable is a legacy class. |
| HashMap is fast. | Hashtable is slow. |
| We can make the HashMap synchronized by calling this code
Map m = Collections.synchronizedMap(hashMap); |
Hashtable is internally synchronized and can't be unsynchronized. |
| HashMap is traversed by Iterator. | Hashtable is traversed by Enumerator and Iterator. |
| Iterator in HashMap is fail-fast. | Enumerator in Hashtable is not fail-fast. |
| HashMap inherits AbstractMap class. | Hashtable inherits Dictionary class. |
13). Differentiate between Iterator and ListIterator
| Basis for comparison | Iterator | ListIterator |
|---|---|---|
| Basic | Iterator can traverse the elements in a collection only in a forward direction. | ListIterator can traverse the elements in a collection in the forward as well as the backward direction.
|
| Add | Iterator is unable to add elements to a collection. | ListIteror can add elements to a collection.
|
| Modify | Iterator can not modify the elements in a collection. | ListIterator can modify the elements in a collection using set(). |
| Traverse | Iterator can traverse Map, List, and Set. | ListIterator can traverse List objects only.
|
| Index | Iterator has no method to obtain an index of the element in a collection. | Using ListIterator, you can obtain an index of the element in a collection. |
14). Differentiate between HashSet and HashMap.
| HashMap | HashTable |
| It is non-synchronized in nature | It is synchronized in nature |
| Allows only one null key but multiple null values | Doesn’t allow any null key or value |
| Has faster processing | has slower processing |
| Can be traversed by Iterator | Can be traversed by Iterator and Enumeration |
| Inherits AbstractMap class | Inherits Dictionary class |
15). Differentiate between Iterator and ListIterator.
| Iterator | ListIterator |
| Can only perform remove operations on the Collection elements | Can perform add, remove and replace operations the Collection elements |
| Can traverse List, Sets and maps | Can traverse only Lists |
| Can traverse the Collection in forward direction | Can traverse the collection in any direction |
| Provides no method to retrieve the index of the element | Provides methods to retrieve the index of the elements |
| iterator() method is available for the entire Collection Framework | listIterator() is only available for the collections implementing the List interface |
16). Differentiate between HashSet and TreeSet.
| Parameters | HashSet | TreeSet |
|---|---|---|
| Ordering or Sorting | It does not provide a guarantee to sort the data. | It provides a guarantee to sort the data. The sorting depends on the supplied Comparator. |
| Null Objects | In HashSet, only an element can be null. | It does not allow null elements. |
| Comparison | It uses hashCode() or equals() method for comparison. | It uses compare() or compareTo() method for comparison. |
| Performance | It is faster than TreeSet. | It is slower in comparison to HashSet. |
| Implementation | Internally it uses HashMap to store its elements. | Internally it uses TreeMap to store its elements. |
| Data Structure | HashSet is backed up by a hash table. | TreeSet is backed up by a Red-black Tree. |
| Values Stored | It allows only heterogeneous values. | It allows only homogeneous values. |
17). Differentiate between ArrayList and Vector.
| ArrayList | Vector |
|---|---|
| ArrayList is not synchronized. | Vector is synchronized. |
| ArrayList increments 50% of the current array size if the number of elements exceeds its capacity. | Vector increments 100% means doubles the array size if the total number of elements exceeds its capacity. |
| ArrayList is not a legacy class. It is introduced in JDK 1.2. | Vector is a legacy class. |
| ArrayList is fast because it is non-synchronized. | Vector is slow because it is synchronized, i.e., in a multithreading environment, it holds the other threads in a runnable or non-runnable state until the current thread releases the lock of the object. |
| ArrayList uses the Iterator interface to traverse the elements. | A Vector can use the Iterator interface or Enumeration interface to traverse the elements. |
18). Difference Between Fail Fast and Fail-Safe Iterators
| Base of Comparison | Fail Fast Iterator | Fail Safe Iterator |
|---|---|---|
| Exception | It throws a ConcurrentModificationException in modifying the object during the iteration process. | It does not throw an Exception. |
| Clone Object | No clone object is created during the iteration process. | A copy or clone object is created during the iteration process. |
| Memory utilization | It requires low memory during the process. | It requires more memory during the process. |
| Modification | It does not allow modification during iteration. | It allows modification during the iteration process. |
| Performance | It is fast. | It is slightly slower than Fail Fast. |
| Examples | HashMap, ArrayList, Vector, HashSet, etc | CopyOnWriteArrayList, ConcurrentHashMap, etc. |
19). Difference List vs ArrayList
| Base of Comparison | List | ArrayList |
|---|---|---|
| Basic | List is an Interface | ArrayList is a standard Collection Class. |
| Extend/Implement | List interface extends Collection Framework. | ArrayList extends AbstractList and implements List Interface. |
| Work | It is used to create a list of elements (objects) that are associated with their index numbers. | ArrayList is used to create a dynamic array that contains objects. |