Search This Blog

Total Pageviews

Java Record Explained

Java introduced the record class in Java 14 as a new type of class primarily intended to model immutable data. A record class provides a concise way to declare classes whose main purpose is to store data. It automatically generates useful methods such as constructors, accessors, equals(), hashCode(), and toString(), making it ideal for representing simple data aggregates.

Here's a breakdown of the components of a record class:

  1. Keyword record: It indicates that this is a record class.

  2. Record Name: The name of the record class.

  3. Components: The fields or components of the record, declared similarly to fields in a regular class. These components are implicitly final.

  4. Constructor(s): The compiler automatically generates a constructor that initializes the components of the record.

  5. Accessor Methods: Accessor methods for each component are generated by default. These methods are named according to the component names.

  6. equals(), hashCode(), and toString(): The compiler automatically generates equals(), hashCode(), and toString() methods based on the components of the record.

Here's a simple example of a record class representing a Point:

public record Point(int x, int y) { // No need to explicitly define constructor, accessors, equals(), hashCode(), or toString() }

With this declaration:

  • You get a constructor Point(int x, int y) that initializes x and y.
  • Accessor methods x() and y() are generated to retrieve the values of x and y.
  • equals(), hashCode(), and toString() methods are automatically generated based on the x and y components.

You can use this record class as you would use any other class:

public class Main { public static void main(String[] args) { Point p1 = new Point(2, 3); Point p2 = new Point(2, 3); System.out.println(p1.equals(p2)); // Output: true System.out.println(p1.hashCode()); // Output: Same hashCode as p2 System.out.println(p1); // Output: Point[x=2, y=3] } }

This example demonstrates how concise and convenient records can be for representing simple data aggregates in Java. They eliminate much of the boilerplate code typically associated with data classes, making code cleaner and more maintainable.

No comments:

BlockingQueue Applications

Java BlockingQueue is a versatile data structure that can be used in various real-time scenarios where multiple threads need to communicate ...