Java Interview Questions

30 Questions
Java

Java

Web DevelopmentBackend

Question 17

What are the differences between List, Set, and Map?

Answer:

In Java, List, Set, and Map are three of the most commonly used collection interfaces, each serving different purposes and having distinct characteristics. Here’s a detailed comparison of their differences:

1. List

Definition: List is an ordered collection (also known as a sequence). Lists can contain duplicate elements and maintain the insertion order.

Key Characteristics:

  • Order: Maintains the order of insertion.
  • Duplicates: Allows duplicate elements.
  • Index-Based Access: Provides positional access via indices.
  • Common Implementations:
    • ArrayList: Resizable array implementation.
    • LinkedList: Doubly-linked list implementation.
    • Vector: Synchronized resizable array implementation (less commonly used in modern code).

Example Usage:

import java.util.ArrayList;
import java.util.List;

public class ListExample {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Apple"); // Allows duplicates

        for (String fruit : list) {
            System.out.println(fruit); // Output: Apple, Banana, Apple
        }
    }
}

2. Set

Definition: Set is a collection that does not allow duplicate elements. It models the mathematical set abstraction and typically does not maintain any particular order.

Key Characteristics:

  • Order: Does not guarantee any specific order (though some implementations do, like LinkedHashSet and TreeSet).
  • Duplicates: Does not allow duplicate elements.
  • Common Implementations:
    • HashSet: Backed by a hash table, does not guarantee any order.
    • LinkedHashSet: Maintains insertion order.
    • TreeSet: Implements NavigableSet, sorted according to the natural ordering of its elements or by a comparator provided at set creation time.

Example Usage:

import java.util.HashSet;
import java.util.Set;

public class SetExample {
    public static void main(String[] args) {
        Set<String> set = new HashSet<>();
        set.add("Apple");
        set.add("Banana");
        set.add("Apple"); // Duplicate element, will not be added

        for (String fruit : set) {
            System.out.println(fruit); // Output: Apple, Banana (order not guaranteed)
        }
    }
}

3. Map

Definition: Map is a collection that maps keys to values. It cannot contain duplicate keys; each key can map to at most one value.

Key Characteristics:

  • Order: Depends on the implementation (e.g., HashMap does not guarantee order, LinkedHashMap maintains insertion order, TreeMap sorts by natural order or a specified comparator).
  • Duplicates: Keys must be unique; values can be duplicated.
  • Key-Value Pairs: Stores entries as key-value pairs.
  • Common Implementations:
    • HashMap: Backed by a hash table, does not guarantee any order.
    • LinkedHashMap: Maintains insertion order.
    • TreeMap: Implements NavigableMap, sorted according to the natural ordering of its keys or by a comparator provided at map creation time.
    • Hashtable: Synchronized version of HashMap (less commonly used in modern code).

Example Usage:

import java.util.HashMap;
import java.util.Map;

public class MapExample {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("Apple", 1);
        map.put("Banana", 2);
        map.put("Apple", 3); // Key "Apple" updated to new value 3

        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue()); // Output: Apple: 3, Banana: 2 (order not guaranteed)
        }
    }
}

Summary of Differences

  1. Purpose:

    • List: Ordered collection with duplicates allowed, suitable for ordered sequences.
    • Set: Unordered collection with no duplicates, suitable for unique elements.
    • Map: Collection of key-value pairs, keys must be unique, suitable for key-based access to values.
  2. Order:

    • List: Maintains insertion order.
    • Set: Does not maintain order (except for LinkedHashSet and TreeSet).
    • Map: Order depends on implementation (HashMap unordered, LinkedHashMap insertion order, TreeMap sorted order).
  3. Duplicates:

    • List: Allows duplicates.
    • Set: Does not allow duplicates.
    • Map: Keys must be unique; values can be duplicated.
  4. Access:

    • List: Indexed-based access.
    • Set: Access via iteration (no direct index-based access).
    • Map: Access via keys.

Conclusion

Understanding the differences between List, Set, and Map is crucial for choosing the right data structure for your specific needs in Java. Each has its own characteristics and use cases, allowing you to efficiently manage and manipulate collections of objects based on the requirements of your application.

Recent job openings