Posted in

COLLECTION FRAMEWORK INTERVIEW QUESTIONS IN JAVA

1. What is the Collection Framework in Java?

The Collection Framework in Java is a set of classes and interfaces that provide ready-to-use data structures like lists, sets, queues, and maps. It supports operations such as adding, removing, searching, and iterating over elements efficiently and consistently across different types of collections.

2. What are the main interfaces in the Java Collections Framework?

The Main Interfaces in Java Collections Framework :

The key interfaces are:

  1. Collection – Root interface for most collections.
  2. List – Ordered collection (e.g., ArrayList, LinkedList).
  3. Set – Unordered collection with no duplicates (e.g., HashSet).
  4. Queue – For holding elements before processing (e.g., PriorityQueue).
  5. Map – Key-value pair collection (e.g., HashMap, TreeMap).

3. What are the advantages of using the Collection Framework?

The Advantages of Using the Collection Framework :

  1. Reusability – Provides ready-made, efficient data structures.
  2. Consistency – Common interfaces and methods across different collections.
  3. Flexibility – Easy to switch between different data structures.
  4. Type Safety – Supports generics for compile-time type checking.
  5. Performance – Optimized implementations for better performance.

4. What is a Set in Java?

  A Set in Java is a collection that does not allow duplicate elements. It models the mathematical set abstraction and is part of the Java Collections Framework.

🔹 Key Features:

  • No duplicates allowed
  • Unordered (in HashSet) or ordered (in LinkedHashSet, TreeSet)
  • Allows at most one null element (except in TreeSet, which doesn’t allow null)

🔹 Common Implementations:

  • HashSet – Unordered, backed by a hash table
  • LinkedHashSet – Maintains insertion order
  • TreeSet – Sorted in natural or custom order

5. What are the main implementations of the Set interface in Java?

The main Implementations of the Set Interface in Java :

  1. HashSet – Unordered, allows one null, fast performance.
  2. LinkedHashSet – Maintains insertion order, allows one null.
  3. TreeSet – Sorted order, does not allow null, based on a Red-Black tree.

6. What are the differences between HashSet, LinkedHashSet, and TreeSet?

Feature HashSet        LinkedHashSet             TreeSet
        OrderNo guaranteed orderMaintains insertion orderMaintains sorted order
    Null ElementsAllows one null elementAllows one null elementDoes not allow null elements
     PerformanceFastest (constant-time operations)Slightly slower than HashSetSlower (logarithmic time operations)
Duplicates Allowed            No         No           No
Use CaseBest for quick lookupsWhen order matters + no duplicatesWhen sorted data is required

7. Can a Set contain null elements? Which types allow it?

Yes, a Set in Java can contain null elements, but it depends on the specific implementation. Both HashSet and LinkedHashSet allow one null element, as they do not rely on natural ordering or comparison when storing elements. However, TreeSet does not allow null elements because it sorts the elements using their natural order or a comparator. Adding a null to a TreeSet will result in a NullPointerException at runtime. Therefore, whether a Set can hold null values depends on how the Set handles ordering and comparisons internally.

8. Explain the difference between Collection and Collections?

Aspect Collection                   Collections
Type  It is a interface.It is a Utility class (final class).
         Package It is present at java.util package.  It is present at java.util package.
         PurposeRoot interface for all collection typesProvides static utility methods for collections
UsageUsed to represent a group of objectsUsed to perform operations like sorting, searching, etc.
        Examples Implemented by List, Set, Queue, etc.Methods like Collections.sort(), Collections.max().

9. How does Java handle duplicate elements in a Set?    

       A Set does not allow duplicate elements. When you try to add a duplicate element, the Set ignores it and retains only unique elements.

10. What is the load factor in HashSet and how does it affect performance?

The load factor in a HashSet is a measure of how full the hash table can get before it is resized. The default load factor is 0.75, meaning the table resizes when 75% full.A lower load factor means less collisions and faster access but uses more memory, while a higher load factor saves memory but may cause more collisions and slower performance.

11. What is a TreeSet in Java?

A TreeSet in Java is a sorted set that stores elements in ascending order and does not allow duplicates. It is based on a Red-Black tree, so operations like add, remove, and search take O(log n) time.

12. What is the difference between TreeSet and HashSet?

Feature TreeSet                      HashSet
Ordering Sorted (natural or custom order)        No guaranteed order
Performance    O(log n) for operationsO(1) for basic operations
Underlying StructureRed-Black Tree Hash Table
                   Allows null Only one null (if comparator allows)One null element allowed
                 Duplicates     Not allowed       Not allowed
                  Use Case   When sorted order is neededWhen fast access is needed

13. How do you use a custom comparator in a TreeSet?

     To use a custom comparator in a TreeSet, you pass the comparator to the TreeSet constructor. Here’s how:

  TreeSet<String> set = new TreeSet<>(new Comparator<String>() {
                 public int compare(String s1, String s2) {
                         return s1.length() – s2.length(); // sort by string length
               }
          });
  This way, TreeSet will sort elements based on your custom logic.

14. What happens if you try to add heterogeneous objects to a TreeSet?

If you try to add heterogeneous objects (different types) to a TreeSet, it will throw a ClassCastException at runtime. This happens because TreeSet needs to compare elements to sort them, and different types usually can’t be compared.

15. What is a LinkedHashSet in Java?

         A LinkedHashSet in Java is a Set that maintains the insertion order of elements. It combines the uniqueness of a HashSet with a linked list to remember the order in which elements were added.

16. What happens if you try to insert duplicate or null values in a LinkedHashSet?

If you try to insert a duplicate in a LinkedHashSet, it is ignored—duplicates are not allowed. You can insert one null value; adding more has no effect since only one null is allowed.

17. What is the difference between ArrayList and LinkedList?

Feature                  ArrayList                  LinkedList
Storage            Dynamic array          Doubly linked list
                Access Time          Fast (O(1) for get/set)        Slower (O(n) for get/set)
              Memory Usage              Less memoryMore memory (extra pointers)
                 IterationFaster due to better cache locality                   Slower
                 Use Case   Frequent access      Frequent insert/delete

18. What is a Vector? How is it different from ArrayList?

A Vector is a legacy class in Java that implements a dynamic array, similar to ArrayList, but it is synchronized.

Here’s the difference between Vector and ArrayList:

                 Feature                    Vector ArrayList
            Thread SafetySynchronized (thread-safe)Not synchronized (not thread-safe)
            PerformanceSlower due to synchronizationFaster in single-threaded contexts
Growth RateDoubles its sizeIncreases by 50%
            Legacy StatusLegacy class (less preferred)Modern and widely used

19. What are the types of Linked Lists?

The main types of Linked Lists are:

  1. Singly Linked List – Each node points to the next node only.
  2. Doubly Linked List – Each node points to both the next and previous nodes.
  3. Circular Linked List – The last node points back to the first node, forming a circle.
  4. Circular Doubly Linked List – Like doubly linked list, but the last node links to the first and vice versa.

20. What are the advantages and disadvantages of LinkedList over ArrayList?

  The advantages and disadvantages of LinkedList over ArrayList:

                 Aspect  LinkedList – Advantage     LinkedList – Disadvantage
Insertion/DeletionFaster in middle (O(1) if position known)Slower at ends if traversal needed
          MemoryNo need to resize like arraysMore memory usage (extra pointers)
PerformanceGood for frequent add/removePoor for random access or small lists
           FlexibilityEasier to implement custom data structuresLess cache-friendly than ArrayList

21. What is the difference between addFirst(), addLast(), and add(index, element) in LinkedList?

   The difference between addFirst(), addLast(), and add(index, element) in a LinkedList:

  • addFirst(element): Adds the element at the beginning of the list.
  • addLast(element): Adds the element at the end of the list.
  • add(index, element): Inserts the element at the specified position in the list.

Each method helps control exactly where the element is placed in the list.

22. How does LinkedList allow null values and duplicates?

  In LinkedList, null values and duplicates are allowed:

  • You can add multiple null elements without any issues.
  • You can also add duplicate elements, and they will be stored in the order they were added.

LinkedList treats all elements as regular objects, so it doesn’t restrict nulls or duplicates.

23. How do you insert a node at the beginning, middle, and end of a singly linked list?

  you can insert a node in a singly linked list:

  1. At the Beginning:
    1. Create a new node.
    1. Point its next to the current head.
    1. Update head to the new node.
  2. In the Middle (at a given position):
    1. Traverse to the node just before the desired position.
    1. Set new node’s next to the current node’s next.
    1. Update current node’s next to the new node.
  3. At the End:
    1. Traverse to the last node.
    1. Set its next to the new node.
    1. Set new node’s next to null.

24. Write a Java method to reverse a singly linked list?

    class Node {
    int data;
    Node next;
    public Node(int data) {
        this.data = data;
        this.next = null;
    }
}
class LinkedList {
    Node head;
    public void reverse() {
        Node prev = null, current = head, next = null;
        while (current != null) {
            next = current.next; 
            current.next = prev; 
            prev = current;      
            current = next;
        }
        head = prev; 
    }
    public void printList() {
        Node temp = head;
        while (temp != null) {
            System.out.print(temp.data + ” “);
            temp = temp.next;
        }
        System.out.println();
    }
}

How it works:

  • reverse() method uses three pointers: prev, current, and next to reverse the list.
  • It iterates through the list and reverses the links.
  • Finally, the head is updated to the last node.

25. What is a doubly linked list?

    A doubly linked list is a type of linked list where each node contains three parts:

  1. Data: The value or data stored in the node.
  2. Next: A reference (pointer) to the next node in the list.
  3. Previous: A reference (pointer) to the previous node in the list.

This allows traversal in both directions: from the head to the tail (forward) and from the tail to the head (backward), unlike a singly linked list, which can only be traversed in one direction.

26. How do you insert or delete a node in a doubly linked list?

 Insertion in Doubly Linked List:

  • At Beginning: New node’s next → head, head’s prev → new node, update head.
  • At End: Traverse to last node, set last’s next → new node, new node’s prev → last.
  • In Middle: Adjust prev and next pointers of surrounding nodes.

Deletion in Doubly Linked List:

  • From Beginning: Move head to head.next, set head.prev → null.
  • From End: Traverse to last, set prev.next → null.
  • Specific Node: Update prev.next and next.prev to skip the node.

27. What is a circular linked list? How does it differ from a regular linked list?

A circular linked list is a type of linked list where the last node points back to the first node, forming a circle. The difference from a Regular Linked List:

Feature Regular Linked List            Circular Linked List
               Last Node            Points to nullPoints to the head node
               Traversal       Ends when null is reachedCan loop continuously unless stopped
               Direction    Can be singly or doubly linkedCan also be singly or doubly linked
               Use Case     Simple linear structuresUseful for circular data like round-robin scheduling

28. How do you detect the start of a loop in a circular linked list?

       To detect the start of a loop in a circular linked list, you can use Floyd’s Cycle Detection Algorithm :

Steps:

  1. Use two pointers: slow (moves one step) and fast (moves two steps).
  2. If they meet, a loop exists.
  3. Reset one pointer to the head, and move both one step at a time.
  4. The point where they meet again is the start of the loop.

29. What are the use cases of circular linked lists?

Here are some common use cases of circular linked lists:

  1. Round-robin scheduling – Tasks are processed in a circular manner (e.g., CPU scheduling).
  2. Circular buffers – For streaming data or buffering (e.g., audio/video buffers).
  3. Playing music/video playlists – Loops back to the first item after the last.
  4. Data structures like queues – Circular linked lists can efficiently manage continuous queues.
  5. Real-time games or apps – For handling repeated or looping states.

30. How do you implement a circular queue using a circular linked list?

To implement a circular queue using a circular linked list:

  • Enqueue: Add a new node at the rear. If the queue is empty, set both front and rear to the new node. Otherwise, update the rear.next to point to the new node and update rear to the new node, linking it back to the front (rear.next = front).
  • Dequeue: Remove the front node. If there’s only one node, set both front and rear to null. Otherwise, update front to front.next and adjust rear.next to the new front.

31. What is a Map in Java?

    A Map is an interface that represents a collection of key-value pairs. Each key is unique, and each key maps to exactly one value. It is part of the java.util package and provides methods for inserting, updating, retrieving, and removing elements based on keys.

Key Points:

  • Key-Value pairs: A Map stores data in pairs, where each key maps to a specific value.
  • Uniqueness of Keys: Each key in a Map is unique; if you try to insert a duplicate key, the existing value is overwritten.

32. What are the main implementations of the Map interface?

The main implementations of the Map interface in Java are:

  1. HashMap: Unordered, allows one null key and multiple null values, provides O(1) time complexity for basic operations.
  2. TreeMap: Sorted by keys, does not allow null keys, O(log n) time complexity for basic operations.
  3. LinkedHashMap: Maintains insertion order (or access order), allows one null key and multiple null values, similar performance to HashMap.
  4. Hashtable: Synchronized, does not allow null keys or values, slower than HashMap.
  5. ConcurrentHashMap: Thread-safe version of HashMap, designed for concurrent access.

33. What is the role of hashCode() and equals() in HashMap?

 In HashMap, the methods hashCode() and equals() are used as follows:

  • hashCode(): Determines the bucket location for the key. It helps in quickly finding the key’s position in the map.
  • equals(): Compares keys within the same bucket to check if they are equal, ensuring no duplicate keys.

Both are essential for the efficient operation of HashMap.

34. What happens if two keys have the same hash code?

If two keys have the same hash code in a HashMap, they are placed in the same bucket. The equals() method is then used to check if the keys are truly equal. If they are equal, the existing key-value pair is updated; otherwise, a new entry is added to the bucket (often using a linked list or tree structure).

35. How does Java handle collisions in HashMap?

       In HashMap, collisions (when two keys have the same hash code) are handled using the following methods:

  1. Linked List (for earlier versions): When multiple keys hash to the same bucket, they are stored as a linked list. Each node in the list contains a key-value pair. If multiple keys hash to the same bucket, the HashMap performs a linear search in the list to find the correct key.
  2. Tree Structure (Java 8 and above): If the number of elements in a bucket exceeds a certain threshold (usually 8), the linked list is converted into a balanced tree (Red-Black tree), improving lookup time from O(n) to O(log n).

36. How does LinkedHashMap differ from HashMap?

Feature HashMap LinkedHashMap
Order of Elements No specific order (unordered)Maintains insertion order (or access order)
PerformanceFaster (no ordering overhead)Slightly slower (due to ordering maintenance)
Use CaseWhen order is not importantWhen order (insertion or access) matters, like caching
Iteration OrderUnpredictablePredictable (insertion or access order)
Underlying StructureHash tableHash table with a linked list

37. How does TreeMap maintain sorting order?

TreeMap maintains sorting order by using a Red-Black tree (a self-balancing binary search tree).

  • The keys in the TreeMap are automatically sorted based on their natural ordering (if they implement Comparable) or a custom comparator (if provided).
  • The keys are arranged in ascending order, and the tree structure ensures that the sorting is maintained during insertion, deletion, and retrieval operations.

This provides logarithmic time complexity (O(log n)) for basic operations like search, insertion, and removal.

38. Can we store a null key or null value in a HashMap? 

     Yes, in a HashMap:

  • One null key is allowed.
  • Multiple null values are allowed.

The HashMap allows the null key because it handles it separately during insertion, and it allows null values because there’s no restriction on storing null values in the map.

39. What happens when you insert heterogeneous keys in a TreeMap?

When you insert heterogeneous keys (keys of different types) in a TreeMap, it will throw a ClassCastException if the keys are not compatible or cannot be compared with each other. This happens because TreeMap requires keys to be comparable, either by implementing the Comparable interface or by providing a custom comparator.

40. What is the difference between HashMap and Hashtable?

          Feature                  HashMap                Hashtable
      Thread SafetyNot thread-safe (not synchronized)Thread-safe (synchronized)
     Null Keys/ValuesAllows one null key and multiple null valuesDoes not allow null keys or null values
       PerformanceFaster due to lack of synchronizationSlower due to synchronization overhead
        Iterator  Uses fail-fast iteratorUses enumeration (not fail-fast)
       IntroducedJava 1.2 (part of Collections framework)Java 1.0 (legacy class)

41. What is the difference between List, Set, and Map?

           Feature                  List                Set               Map
          DuplicatesAllows duplicatesDoes not allow duplicatesKeys are unique, but values can be duplicated
          OrderingMaintains insertion order (e.g., ArrayList, LinkedList)No guaranteed order (unless using LinkedHashSet or TreeSet)Maintains order (e.g., LinkedHashMap) or sorted order (e.g., TreeMap)
IndexingElements can be accessed via indexNo indexing; access is through iterationKeys are used for accessing values (no indexing)
         Common ImplementationsArrayList, LinkedList, VectorHashSet, LinkedHashSet, TreeSetHashMap, LinkedHashMap, TreeMap
Use CaseWhen you need ordered elements with possible duplicatesWhen you need unique elementsWhen you need key-value pairs for fast lookups

42. What is the difference between HashMap and TreeMap?

Feature HashMap                       TreeMap
OrderDoes not maintain any order.Maintains sorted order of keys, based on their natural ordering or a custom comparator.
ImplementationUses a hash table for storage.Uses a Red-Black tree for storage.
Null Keys/ValuesAllows one null key and multiple null values.Does not allow null keys, but allows null values.
PerformanceFaster for basic operations (O(1) on average).Slower due to sorting (O(log n) for basic operations).
Use CaseWhen order is not important.When sorted order of keys is required.

43. What are the differences between Comparable and Comparator?

                Feature Comparable            Comparator
           Purpose Used to define the natural ordering of objects.Used to define custom ordering of objects.
         Implemented byThe class of the object being compared.A separate class or object (can be external).
         Method UsedcompareTo(Object obj)compare(Object obj1, Object obj2)
Modifies ObjectModifies the class whose objects are being compared.Does not modify the objects, it’s external.
SortingObjects are sorted based on their natural order.Allows flexible sorting, can define multiple sorting strategies.

44. Why are Map keys usually immutable?

Map keys are usually immutable to ensure:

  1. Consistency in hashing and equality checks (hashCode() and equals()), preventing issues if the key’s state changes.
  2. Thread safety, as immutable objects cannot be modified after creation.

This ensures reliable and correct behavior when using keys in a Map.

45. What are the thread-safe classes in the Java Collection Framework?

The thread-safe classes in the Java Collection Framework include:

  1. Vector: A thread-safe List implementation, though less commonly used now due to performance overhead.
  2. Hashtable: A thread-safe Map implementation, but slower compared to HashMap due to synchronization.
  3. Stack: A thread-safe class that represents a last-in, first-out (LIFO) stack, built on top of Vector.
  4. ConcurrentHashMap: A thread-safe Map that allows concurrent access with better performance than Hashtable.
  5. CopyOnWriteArrayList: A thread-safe List that creates a new copy of the underlying array when modified.
  6. CopyOnWriteArraySet: A thread-safe Set implemented using CopyOnWriteArrayList.

46. What are NavigableSet and NavigableMap?

 NavigableSet and NavigableMap are extended versions of SortedSet and SortedMap that provide additional methods for navigating through sorted collections:

  • NavigableSet: Extends SortedSet, offering methods like lower(), floor(), ceiling(), higher(), pollFirst(), and pollLast() for navigating elements.
    • Example: TreeSet.
  • NavigableMap: Extends SortedMap, offering methods like lowerKey(), floorKey(), ceilingKey(), higherKey(), pollFirstEntry(), and pollLastEntry() for navigating key-value pairs.
    • Example: TreeMap.

47. How does Java handle collisions in HashMap?

HashMap handles collisions using buckets and linked lists (or balanced trees starting from Java 8). When two keys hash to the same bucket (i.e., they have the same hash code), HashMap resolves the collision by storing the key-value pairs in a linked list at that bucket. If the list becomes too long (i.e., more than 8 entries), it may be converted into a balanced tree (such as a Red-Black tree) to improve performance for lookups.

48. What is the initial capacity of HashMap and why is it important?

The initial capacity of a HashMap in Java is 16 by default. It represents the number of buckets the HashMap can hold initially. The initial capacity is important because it determines how often the HashMap needs to resize (rehash) as elements are added. Setting an appropriate initial capacity can improve performance by reducing the number of resizing operations, especially when the number of entries is known in advance.

49. What is a Stack in Java and which class implements it?

A Stack in Java is a collection that follows the Last In, First Out (LIFO) principle, meaning the last element added is the first one to be removed. The Stack class in Java, which is part of the java.util package, implements this data structure. It provides methods like push(), pop(), peek(), and isEmpty() for managing elements. However, it is considered somewhat outdated, and the Deque interface (implemented by classes like ArrayDeque) is often recommended for stack-like operations.

50. What are the main operations of a Stack?

 The main operations of a Stack are:

  1. push(): Adds an element to the top of the stack.
  2. pop(): Removes and returns the element from the top of the stack.
  3. peek(): Returns the element at the top of the stack without removing it.
  4. isEmpty(): Checks if the stack is empty.
  5. size(): Returns the number of elements in the stack (optional in some implementations).

51. How to reverse a string using Stack in Java?

   To reverse a string using a Stack in Java, you can push each character of the string onto the stack and then pop the characters to construct the reversed string.

Example:

   import java.util.Stack;
    public class ReverseString {
    public static String reverse(String str) {
        Stack<Character> stack = new Stack<>();   
        for (int i = 0; i < str.length(); i++) {
            stack.push(str.charAt(i));
        }
        StringBuilder reversed = new StringBuilder();
        while (!stack.isEmpty()) {
            reversed.append(stack.pop());
        }
        return reversed.toString();
    }
    public static void main(String[] args) {
        String original = “hello”;
        System.out.println(reverse(original)); 
    }
}

52. What is a Queue in Java?

            A Queue in Java is a collection that follows the First In, First Out (FIFO) principle. The first element added is the first one to be removed. Common operations include:

  • offer(): Adds an element to the queue.
  • poll(): Removes and returns the front element.
  • peek(): Returns the front element without removing it.
  • isEmpty(): Checks if the queue is empty.

Java provides LinkedList and PriorityQueue as implementations of the Queue interface.

53. What are the different types of Queues in Java?

The main types of queues are:

  1. LinkedList: Implements the Queue interface, providing basic FIFO queue functionality. It supports dynamic sizing and allows adding/removing elements from both ends.
  2. PriorityQueue: A queue where elements are ordered based on their priority. The element with the highest priority is dequeued first.
  3. ArrayDeque: A resizable array-based implementation of the Deque interface, used as a queue. It is faster than LinkedList for most queue operations.
  4. BlockingQueue (e.g., ArrayBlockingQueue, LinkedBlockingQueue): A thread-safe queue used in concurrent programming, where threads are blocked if they attempt to dequeue from an empty queue or enqueue to a full one.
  5. Deque (Double Ended Queue): Supports adding/removing elements from both ends, and can function as both a queue and a stack (e.g., ArrayDeque, LinkedList).

54. What is the difference between Queue, Deque, and PriorityQueue?

   The differences between Queue, Deque, and PriorityQueue in Java are:

  1. Queue:
    • Follows FIFO (First In, First Out) principle.
    • Elements are added at the end and removed from the front.
    • Examples: LinkedList, ArrayDeque.
  2. Deque (Double Ended Queue):
    • Allows adding/removing elements from both ends (front and back).
    • Can function as both a stack (LIFO) and a queue (FIFO).
    • Examples: ArrayDeque, LinkedList.
  3. PriorityQueue:
    • Elements are ordered based on their natural order or a custom comparator.
    • Does not follow FIFO; the element with the highest priority (smallest or largest) is dequeued first.
    • Example: PriorityQueue.

55. What are the different types of Queue implementations in Java?

The different types of Queue implementations in Java are:

  1. LinkedList: Implements the Queue interface, supports dynamic sizing, and allows adding/removing elements from both ends (FIFO).
  2. ArrayDeque: A resizable array-based implementation of the Deque interface, offering faster performance than LinkedList for most queue operations.
  3. PriorityQueue: A queue where elements are ordered based on their priority, not FIFO. The element with the highest priority is dequeued first.
  4. ArrayBlockingQueue: A thread-safe, bounded queue that blocks threads when full or empty. It is commonly used in concurrent programming.
  5. LinkedBlockingQueue: A thread-safe, optionally bounded queue that can be used in multi-threaded environments, allowing threads to block when necessary.

 These implementations are found in the java.util and java.util.concurrent packages.

56. How is PriorityQueue implemented in Java?

PriorityQueue is implemented using a heap, specifically a binary heap (min-heap by default). It orders elements based on their natural ordering or a custom comparator provided during its creation.

Key points:

  • Min-Heap: The element with the highest priority (smallest element for natural ordering) is at the root and dequeued first.
  • Custom Comparator: You can provide a comparator to define custom priority ordering (e.g., max-heap).
  • Dynamic Size: It automatically resizes as elements are added or removed.

57. What is the difference between Stack and Queue?

               Feature                      Stack Queue
Order of OperationFollows LIFO (Last In, First Out)Follows FIFO (First In, First Out)
Primary Operationspush(), pop(), peek(), isEmpty()offer(), poll(), peek(), isEmpty()
Use CaseUsed in scenarios like undo operations, recursion, backtrackingUsed in scenarios like task scheduling, breadth-first search, buffering
       Element RemovalRemoves the last added elementRemoves the first added element
ExampleBrowser history, function call stackPrinter queue, task scheduling

58. What is an Iterator in Java? Why is it used?

    An Iterator in Java is used to traverse collections like List, Set, and Map. It allows accessing elements one by one and safely removing them during iteration.

Common methods:

  • hasNext(): Checks if more elements exist.
  • next(): Returns the next element.
  • remove(): Removes the current element.

It provides a standard way to loop through different collection types.

59. Explain the difference between Iterator and ListIterator?

Feature Iterator ListIterator
Applicable ToAll collections (List, Set, etc.)Only for List types
DirectionTraverses in forward direction onlyTraverses in both forward and backward directions
Element ModificationCan remove elementsCan add, remove, and replace elements
Index AccessNo index accessCan get index of previous/next element
MethodshasNext(), next(), remove()hasNext(), next(), hasPrevious(), previous(), add(), set(), remove().

60. What are the hasNext(),next(), and remove()  methods of the iterator interface?

The Iterator interface in Java provides the following methods:

  1. hasNext():
    1. Returns true if there are more elements to iterate over, otherwise false.
  2. next():
    1. Returns the next element in the iteration and advances the iterator.
  3. remove():
    1. Removes the last element returned by the iterator from the underlying collection. This method can be called only once per call to next().

  These methods allow you to safely traverse and modify a collection during iteration.

Leave a Reply

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