How is the Java Collections Framework organised, and what are the main interfaces?
The framework is built around a small number of interfaces, with the implementation classes behind them. Two roots matter: Collection, which is extended by List, Set and Queue, and Map, which stands apart because it maps keys to values rather than holding elements.
The core interfaces and what they promise. List is ordered and allows duplicates — you can get an element by index. Set is a collection with no duplicate elements, so it models uniqueness. SortedSet and NavigableSet add ordering and navigation operations. Queue and Deque model a FIFO or LIFO collection. Map is a key-value dictionary, and its sorted variant SortedMap keeps its keys in order.
Behind those sit the implementations you use every day: ArrayList and LinkedList for lists, HashSet, LinkedHashSet and TreeSet for sets, HashMap, LinkedHashMap and TreeMap for maps, and ArrayDeque and PriorityQueue for queues. The interface is the contract, the class is one implementation of it, and you should depend on the interface.
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
public class Main {
public static void main(String[] args) {
// List: ordered, duplicates allowed.
List<String> list = new ArrayList<>(Arrays.asList("b", "a", "b"));
System.out.println("list : " + list);
// Set: unique elements.
Set<String> set = new LinkedHashSet<>(Arrays.asList("b", "a", "b"));
System.out.println("set : " + set);
// Map: key to value.
Map<String, Integer> map = new LinkedHashMap<>();
map.put("a", 1);
map.put("b", 2);
System.out.println("map : " + map);
// Queue: first in, first out.
Queue<String> queue = new ArrayDeque<>(Arrays.asList("x", "y"));
System.out.println("queue : " + queue);
}
}The output shows the defining behaviour of each. The list keeps all three elements including the duplicate b. The set drops the duplicate. The map stores two key-value pairs. And the queue is ready to be polled in insertion order.