Sobes.tech
Middle

Describe the hierarchy of collections in Java.

sobes.tech AI

Answer from AI

Collection hierarchy in Java is based on a set of interfaces that provide a standard way to represent groups of objects.

Main interfaces:

  • Collection: the root interface of the hierarchy. Defines basic operations applicable to all collections: add, remove, check for elements, determine size.
  • Set: a collection that does not contain duplicates and has no specific order of elements.
  • List: an ordered collection with access to elements by index. Can contain duplicates.
  • Queue: a collection designed for storing elements before processing. Usually follows FIFO (First-In, First-Out) rule, but there are other implementations.
  • Deque: a double-ended queue. Supports adding and removing elements from both ends.
  • Map: a collection that stores key-value pairs. Keys must be unique. Does not extend the Collection interface.

Main implementing classes (examples):

Interface Implementing classes (examples) Description
Set HashSet, LinkedHashSet, TreeSet No duplicates. HashSet - unordered, LinkedHashSet - preserves insertion order, TreeSet - sorted.
List ArrayList, LinkedList, Vector Ordered. ArrayList - array-based, LinkedList - linked list-based, Vector - synchronized (deprecated).
Queue LinkedList, PriorityQueue For processing. LinkedList - FIFO, PriorityQueue - based on priorities.
Deque ArrayDeque, LinkedList Double-ended queue. ArrayDeque - array-based, LinkedList - linked list-based.
Map HashMap, LinkedHashMap, TreeMap, Hashtable Key-value. HashMap - unordered, LinkedHashMap - preserves insertion/access order, TreeMap - sorted by keys, Hashtable - synchronized (deprecated).

Example of using ArrayList:

// Creating an ArrayList of strings
List<String> fruits = new ArrayList<>();
// Adding elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
// Access by index
String firstFruit = fruits.get(0); // Apple
// Collection size
int size = fruits.size(); // 3

Example of using HashSet:

// Creating a HashSet of integers
Set<Integer> numbers = new HashSet<>();
// Adding elements (duplicates are ignored)
numbers.add(1);
numbers.add(2);
numbers.add(2); // Ignored
// Collection size
int size = numbers.size(); // 2

Example of using HashMap:

// Creating a HashMap: key - String, value - Integer
Map<String, Integer> ages = new HashMap<>();
// Adding key-value pairs
ages.put("Alice", 30);
ages.put("Bob", 25);
// Getting value by key
int aliceAge = ages.get("Alice"); // 30
// Checking for key existence
boolean hasBob = ages.containsKey("Bob"); // true