List, Set, and Map
The Collections Framework provides reusable data structures and algorithms. List preserves order and allows duplicates. Set models uniqueness. Map associates keys with values.
List<String> names = new ArrayList<>();
names.add("A");
names.add("B");
Set<String> unique = new HashSet<>(names);
Map<String, Integer> counts = new HashMap<>();
counts.merge("java", 1, Integer::sum);
ArrayList is usually the default list. HashSet and HashMap provide average constant-time lookup under good hashing behavior. LinkedHashMap preserves insertion order, while TreeMap keeps keys sorted.
Key Takeaways
- Choose collections based on required semantics.
ArrayListis a strong default for indexed/sequential lists.- Hash-based structures depend on correct
equalsandhashCode.