Immutable

2 posts in this section

Collection Factory Methods (JEP 269): Immutable List, Set, and Map

Why Collection Factory Methods? Before Java 9, creating a small immutable collection was tedious: // Java 8 — three lines, two classes, mutable intermediate List<String> names = Collections.unmodifiableList( Arrays.asList("Alice", "Bob", "Charlie") ); // Java 8 — even worse for Map Map<String, Integer> scores = new HashMap<>(); scores.put("Alice", 90); scores.put("Bob", 85); Map<String, Integer> immutableScores = Collections.unmodifiableMap(scores); JEP 269 (Java 9) introduced static factory methods that create truly immutable collections with a single expression:

Continue reading »

Records (JEP 395): Immutable Data Classes Without the Boilerplate

Finalized in Java 16 (JEP 395). Available in all Java 16+ releases, including Java 17. Previous previews: Java 14 (JEP 359) and Java 15 (JEP 384). The Problem: Data Classes in Java Writing a simple immutable data class in Java 11 requires significant boilerplate: public final class Point { private final int x; private final int y; public Point(int x, int y) { this.x = x; this.y = y; } public int x() { return x; } public int y() { return y; } @Override public boolean equals(Object o) { if (this == o) return true; if (!

Continue reading »