List and Set
Description
List preserves order; Set keeps unique values.
Explanation
ArrayList is a common List implementation and HashSet is a common Set implementation.
Example
java.util.List<String> names = new java.util.ArrayList<>();← Chapter 8 — Exceptions & Collections
mixed
The Collections Framework provides reusable structures for groups of objects. List keeps ordered items, Set avoids duplicates, and Map associates keys with values.
Generics declare the type a collection should hold. They let the compiler catch mixing an Integer into a list of String names.
List preserves order; Set keeps unique values.
ArrayList is a common List implementation and HashSet is a common Set implementation.
java.util.List<String> names = new java.util.ArrayList<>();Map stores key-value pairs.
A key identifies its associated value.
java.util.Map<String, Integer> scores = new java.util.HashMap<>();Choose a collection based on the operations you need, not only its name. For example, use a Map when looking up Rohan's score by name is central to the task.
import java.util.ArrayList;
import java.util.List;
public class CollectionDemo {
public static void main(String[] args) {
List<String> learners = new ArrayList<>();
learners.add("Aditi");
learners.add("Rohan");
System.out.println(learners);
}
}