Java records

Java records

It’s provide a streamlined way to define classes that are primarily meant for holding immutable data. They allow developers to define data carrier objects without boilerplate code, such as getters, toString(), equals(), and hashCode() methods.

Key characteristics of Java records:

  • Records are immutable by default, meaning their state cannot change after creation.
  • They are useful for creating simple data containers with fixed values at the time of instantiation.

Caveat with Mutable Objects:

Although records ensure that the fields themselves are final, if those fields contain mutable objects (like a list or a map), the contents of those objects can still be changed. The immutability only applies to the reference, not to the object being referenced.

Example:

import java.util.List;

public record Person(String name, List<String> hobbies) {}

Person p = new Person(“Kevin”, List.of(“Coding”, “Reading”));
p.hobbies().add(“Gaming”); // This will throw an UnsupportedOperationException if the list is immutable.

While the reference to the list (hobbies) is final, the list itself can still be modified unless you take steps to make it immutable.

import java.util.List;
import java.util.Collections;

public record Person(String name, List<String> hobbies) {
public Person {
// Create an unmodifiable copy of the list to prevent mutations
hobbies = Collections.unmodifiableList(hobbies);
}
}

Person p = new Person(“Kevin”, List.of(“Coding”, “Reading”));
// This will now throw an UnsupportedOperationException because the list is immutable
p.hobbies().add(“Gaming”);


Discover more from Kvnbbg.fr

Subscribe to get the latest posts sent to your email.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *