Sobes.tech
Junior

What collections exist in Java?

sobes.tech AI

Answer from AI

In Java, the following main collection interfaces are part of the Java Collections Framework:

  • Collection: The basic interface defining common operations on groups of objects. It is extended by sub-interfaces:

    • List: An ordered collection (sequence). Elements can repeat. Supports access by index.
      • ArrayList: Resizable array. Good for fast access by index and appending at the end. Slow for inserting/removing in the middle.
      • LinkedList: Doubly linked list. Good for inserting/removing at the beginning or end. Slow for access by index.
      • Vector: Synchronized version of ArrayList. Considered outdated.
      • Stack: Extends Vector, implements stack behavior (LIFO).
    • Set: A collection containing only unique elements. No guaranteed order.
      • HashSet: Implemented using a hash table. The fastest for add, remove, and contains operations. Does not guarantee order.
      • LinkedHashSet: Implemented as a hash table + linked list. Guarantees insertion order.
      • TreeSet: Implemented with a red-black tree. Stores elements in sorted order. Slower than HashSet, but faster than LinkedHashSet for range searches.
    • Queue: A collection designed for holding elements prior to processing (FIFO - First-In, First-Out).
      • PriorityQueue: Elements are stored according to their natural order or comparator. Retrieves the highest priority.
      • Deque: (Double Ended Queue) Supports insertion and removal at both ends.
        • ArrayDeque: Array-based implementation of Deque. More efficient than LinkedList as a queue/stack.
  • Map: A collection that stores key-value pairs. Keys are unique.

    • HashMap: Implemented using a hash table. The fastest for add, remove, and contains operations. Does not guarantee key order.
    • LinkedHashMap: Implemented as a hash table + linked list. Guarantees insertion order or access order.
    • TreeMap: Implemented with a red-black tree. Stores key-value pairs in sorted order by keys. Slower than HashMap.
    • Hashtable: Synchronized version of HashMap. Considered outdated.

There are also outdated classes not part of the JCF but sometimes encountered:

  • Vector
  • Stack
  • Hashtable
  • Enumeration (interface)