Collections
Organizing your objects.
Collections
Analogy: organization
Collections are like Containers for your objects.
- List: Like a Shopping List. Order matters, and you can write "Milk" twice.
- Set: Like a Coin Collection. You only keep unique coins. No duplicates allowed!
- Map: Like a Dictionary. You look up a word (Key) to find its definition (Value).
The Sorting Hat
Throw items into the collection and see what happens!
- Try adding duplicates to a Set.
- Try adding items to a List.
- Try Key-Value pairs in a Map.
The Sorting Hat (Collections)
List: Ordered collection. Duplicates allowed.
Collection is empty
The Code
Java provides the Collection framework.
Java Example
Switch language in Navbar
// List: Ordered, Duplicates OK
List<String> shopping = new ArrayList<>();
shopping.add("Milk");
shopping.add("Milk"); // OK!
// Set: Unique Only
Set<String> coins = new HashSet<>();
coins.add("Quarter");
coins.add("Quarter"); // Ignored!
// Map: Key-Value Pairs
Map<String, String> dictionary = new HashMap<>();
dictionary.put("Java", "A programming language");
Up Next
Generics