How is the Java Collections Framework organised, and what are the main interfaces?
The Collections Framework is built around one root interface and a small number of interfaces that branch out from it.
The root interface is Collection, and it describes anything that holds a group of objects. Below it there are three important branches. The interface List holds an ordered group where the same object may appear more than once. The interface Set holds a group where every object appears at most once. The interface Queue holds a group that is processed in a particular order, and Deque extends it to allow working from both ends.
The interface Map sits outside all of this, because a map is not a collection of objects but a way of pairing keys with values.
Collection
|-- List ordered, duplicates allowed (ArrayList, LinkedList, Vector)
|-- Set no duplicates (HashSet, LinkedHashSet, TreeSet)
'-- Queue processed in order (PriorityQueue)
'-- Deque both ends (ArrayDeque)
Map (separate) (HashMap, LinkedHashMap, TreeMap)
Each of these interfaces is a contract, and there are several implementations of each one. The usual advice is to write your code against the interface and to choose the implementation when you build it, because that way you can change the choice later without changing every line that uses it.
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<String>();
names.add("Ada");
names.add("Ada");
Set<String> unique = new HashSet<String>(names);
Map<String, Integer> counts = new HashMap<String, Integer>();
counts.put("Ada", 1);
Map<String, Integer> ordered = new LinkedHashMap<String, Integer>(counts);
System.out.println("names : " + names.size());
System.out.println("unique : " + unique.size());
System.out.println("map : " + counts.get("Ada"));
System.out.println("ordered: " + ordered.get("Ada"));
}
}
The next question in this topic looks at the differences between the main four.