Sobes.tech
Junior

What are the implementations of collections in the Java programming language?

sobes.tech AI

Answer from AI

  • Interfaces:

    • Collection: The base interface for all collections.
    • List: An ordered collection (with indices).
    • Set: A collection that does not contain duplicates.
    • SortedSet: A collection that does not contain duplicates, with elements sorted.
    • Map: An associative array (key-value pairs).
    • SortedMap: An associative array sorted by keys.
    • Queue: A collection for storing elements before processing.
    • Deque: A double-ended queue.
  • Classes (main implementations):

    • For List:

      • ArrayList: Dynamic array. Fast access by index, slow insert/delete in the middle.
      • LinkedList: Doubly linked list. Slow access by index, fast insert/delete in the middle.
      • Vector: Deprecated synchronized version of ArrayList.
      • Stack: Subclass of Vector, implements a stack (LIFO).
    • For Set:

      • HashSet: Hash table based implementation. Does not guarantee order.
      • LinkedHashSet: Hash table + linked list. Preserves insertion order.
      • TreeSet: Red-black tree based implementation. Elements sorted in ascending order.
    • For Map:

      • HashMap: Hash table based implementation. No guaranteed order.
      • Hashtable: Deprecated synchronized version of HashMap.
      • LinkedHashMap: Hash table + linked list. Preserves insertion order.
      • TreeMap: Red-black tree based implementation. Sorted by keys.
    • For Queue:

      • PriorityQueue: Queue with priority, elements dequeued according to natural order or comparator.
      • ArrayDeque: Double-ended queue based on array.
  • Utilities:

    • Collections: Static methods for working with collections (sorting, searching, synchronization, etc.).
// Example of using ArrayList
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
System.out.println(names.get(0)); // Alice
// Example of using HashSet
Set<Integer> numbers = new HashSet<>();
numbers.add(1);
numbers.add(2);
numbers.add(1); // Duplicate will not be added
System.out.println(numbers.size()); // 2
// Example of using HashMap
Map<String, Integer> ages = new HashMap<>();
ages.put("Alice", 30);
ages.put("Bob", 25);
System.out.println(ages.get("Alice")); // 30
// Example of using PriorityQueue
Queue<Integer> priorityQueue = new PriorityQueue<>();
priorityQueue.add(3);
priorityQueue.add(1);
priorityQueue.add(2);
System.out.println(priorityQueue.poll()); // 1 (lowest priority)