Collections Framework
Unlike raw arrays, Java Collections provide dynamic resizing frameworks. The framework includes lists, sets, and key-value maps to store objects.
1 Collection Architecture: List, Set, and Map
The primary elements of the collection framework are:
- List (ArrayList): An ordered container that allows duplicates. Excellent for random index access.
- Set (HashSet): An unordered container that rejects duplicates. Quick validation checks for existence.
- Map (HashMap): Stores key-value pairings (e.g. usernames paired with user IDs). Keys must be unique.
⚠️ Wrapper Class Notice: Collections can only store Objects, not raw primitives. If you want to store integers inside an ArrayList, Java uses Auto-boxing to convert `int` primitives into their object wrappers automatically: `ArrayList<Integer> list = new ArrayList<>();`.
2 Collections Operations
Let's run a program declaring Lists, Sets, and Maps, performing insertions and reads:
Java — Collections Framework
▶ Run Code
import java.util.ArrayList;
import java.util.HashSet;
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
// ArrayList: Ordered list
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Apple"); // Duplicates allowed
System.out.println("List: " + list);
// HashSet: Unique values
HashSet<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Apple"); // Duplicate ignored
System.out.println("Set: " + set);
// HashMap: Key-Value pairs
HashMap<String, Integer> map = new HashMap<>();
map.put("Alice", 95);
map.put("Bob", 88);
System.out.println("Map: " + map);
System.out.println("Bob's Score: " + map.get("Bob"));
}
}
3 Code Challenge
Challenge: Write a program that instantiates an `ArrayList` of integers, adds 5 arbitrary values, removes the value at index 2, and prints the list. Then declare a `HashMap` to map product names (String) to prices (Double). Add items and print price values.