Let’s continue with our lessons during this corona lockdown. In the last two posts we discussed textblocks and instanceof in Java 13 and 14.
In this post, we’ll discuss a very cool feature introduced in Java 14, record.
Say, you have a shopping cart that is a collection of ShoppingItem with id, name, price and quantity members. Building this will involve writing so many lines of code as shown below.
class ShoppingItem { private int id; private String name; private double price; private int quantity; public ShoppingItem(int id, String name, double price, int quantity) { this.id = id; this.name = name; this.price = price; this.quantity = quantity; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public int hashCode() { return id; } public boolean equals(Object obj) { if(obj instanceof ShoppingItem item) { return item.id == this.id; } return false; } public String toString() { return name; } } public class RecordsExample { public static void main(String[] args) { ShoppingItem book = new ShoppingItem(21321, "Programming Java", 12.34, 1); ShoppingItem mobile = new ShoppingItem(21233, "iPhone 11 pro", 999, 1); List<ShoppingItem> cart = Arrays.asList(book, mobile); cart.forEach(System.out::println); } }
Phew! That’s lot of code for just storing some data
Image source: https://blog.submain.com/evaluate-code-readability/
Enter record
ShoppingItem class can be replaced with just one line code using a record. If you define a class as record with the members, the hashCode(), equals(), toString(), getters/setters are automatically generated for you by the compiler. So the code using record is as shown below.
public class RecordsExample { record ShoppingItem(int id, String name, double price, int quantity) {} public static void main(String[] args) { ShoppingItem book = new ShoppingItem(21321, "Programming Java", 12.34, 1); ShoppingItem mobile = new ShoppingItem(21233, "iPhone 11 pro", 999, 1); List<ShoppingItem> cart = Arrays.asList(book, mobile); cart.forEach(System.out::println); } }
This one line
record ShoppingItem(int id, String name, double price, int quantity) {}
does the trick
Record in Java, in short is a data class or a tuple that’s a simple data structure.
Please remember to compile using –enable-preview and –release 14 switches