Sobes.tech
Junior

What collections exist in Java?

sobes.tech AI

Answer from AI

Collection - the root interface of the collection hierarchy. It represents a group of objects known as elements. It is extended by interfaces List, Set, Queue.

List - an ordered collection that allows duplicates. Implementations:

  • ArrayList: a dynamic array, provides quick access by index, slow deletion/insertion in the middle.
  • LinkedList: a doubly linked list, provides fast insertion/deletion, slow access by index.
  • Vector: a synchronized version of ArrayList, deprecated, use only when thread safety is needed.
  • Stack: inherits from Vector, implements LIFO (Last-In, First-Out).

Set - an unordered collection that does not allow duplicates. Implementations:

  • HashSet: uses a hash table, fast add, remove, search operations, element order is not guaranteed.
  • LinkedHashSet: maintains insertion order, uses a hash table and linked list.
  • TreeSet: stores elements in sorted order, uses a red-black tree.

Queue - a collection designed for holding elements prior to processing (a queue). Usually operates on FIFO (First-In, First-Out) principle. Implementations:

  • LinkedList: can be used as a Queue.
  • ArrayDeque: a double-ended queue, can work as a stack and queue.
  • PriorityQueue: elements are retrieved in order of priority.

Map - an interface, not part of the Collection hierarchy, but often considered together. Stores key-value pairs, keys are unique. Implementations:

  • HashMap: uses a hash table, fast operations, element order is not guaranteed.
  • LinkedHashMap: maintains insertion or access order.
  • TreeMap: stores key-value pairs in sorted order by keys, uses a red-black tree.
  • Hashtable: a synchronized version of HashMap, deprecated.

Examples of usage:

import java.util.*;

public class CollectionExamples {

    public static void main(String[] args) {
        // ArrayList
        List<String> arrayList = new ArrayList<>();
        arrayList.add("Apple");
        arrayList.add("Banana");
        System.out.println(arrayList.get(0));

        // HashSet
        Set<Integer> hashSet = new HashSet<>();
        hashSet.add(1);
        hashSet.add(2);
        hashSet.add(1); // duplicate will not be added
        System.out.println(hashSet.size());

        // HashMap
        Map<String, String> hashMap = new HashMap<>();
        hashMap.put("key1", "value1");
        hashMap.put("key2", "value2");
        System.out.println(hashMap.get("key1"));
    }
}

Brief table:

Interface Main implementations Features
List ArrayList, LinkedList Ordered, allows duplicates
Set HashSet, TreeSet No duplicates
Queue LinkedList, PriorityQueue Storage for processing, usually FIFO
Map HashMap, TreeMap Key-value pairs, unique keys