JVM / Java / Collections / Framework
1. Java Collections Framework (JCF)
In Java, Collections are a full arhitecture of interfaces, classes, utilities.
They are part of the Java Collection Framework (JCF), located in java.util package.
The JCF provides:
- Interfaces (List, Set, Map, Queue)
- Implementations (ArrayList, HashSet, HashMap, LinkedList)
- Algorithms (sorting, searching)
Iterable
|
Collection
┌───────────┼──────────┐
| | |
List Set Queue
| | |
ArrayList HashSet ArrayDeque
LinkedList TreeSet PriorityQueue
Map
|
HashMap
TreeMap
2. Collection Interface
The Collectioin Interface represents a group of objects (like a bag).
Main subinterfaces:
- List (ordered, indexed access): ArrayList, LinkedList
- Set (no duplicates): HashSet (unordered), TreeSet (ordered)
- Queue/Deque (FIFO/LIFO): LinkedList, ArrayDeque
3. Map Interace
Map is NOT a subtype of Collection.
Stores key-value pairs:
- HashMap
- LinkedHashMap
- TreeMap
4. Collections vs Arrays
Arrays:
- fixed size
- can store primitives
- no built-in utilities
- hard to manipulate
Collections:
- dynamic size
- store objects (but wrappers allow primitives)
- rich functionality
- easy add/remove/find
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class JCF {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Alex");
names.add("Maria");
for (String n : names) {
System.out.println(n);
}
Set<String> cities = new HashSet<>();
cities.add("Bucharest");
cities.add("Cluj");
cities.add("Bucharest");
for (String c : cities) {
System.out.println(c);
}
Map<String, Integer> ages = new HashMap<>();
ages.put("Ana", 25);
ages.put("Bogdan", 32);
ages.put("Ana", 26);
for (Map.Entry<String, Integer> entry : ages.entrySet()) {
System.out.println(
entry.getKey() + " -> " + entry.getValue()
);
}
}
}