Add java17-features module: runnable demos and captured output for the ankurm.com java17-features article
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
/** Records (final in 16, JEP 395): what the compiler generates, compact constructors, and the shallow-immutability caveat. */
|
||||
public class RecordsDemo {
|
||||
record Point(int x, int y) {
|
||||
Point { if (x < 0 || y < 0) throw new IllegalArgumentException("negative coordinate: " + x + "," + y); }
|
||||
double distance() { return Math.sqrt(x * x + y * y); }
|
||||
}
|
||||
record Team(String name, java.util.List<String> members) {}
|
||||
|
||||
public static void main(String[] args) {
|
||||
Point p = new Point(3, 4);
|
||||
System.out.println("toString : " + p);
|
||||
System.out.println("equals : " + p.equals(new Point(3, 4)) + " hashCode equal: " + (p.hashCode() == new Point(3, 4).hashCode()));
|
||||
System.out.println("accessor : p.x() = " + p.x() + ", distance = " + p.distance());
|
||||
try { new Point(-1, 2); } catch (IllegalArgumentException e) { System.out.println("compact ctor : " + e.getMessage()); }
|
||||
|
||||
java.util.List<String> list = new java.util.ArrayList<>(java.util.List.of("a"));
|
||||
Team t = new Team("core", list);
|
||||
list.add("b");
|
||||
System.out.println("shallow : " + t + " <- the record's list changed after construction");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user