tl;dr
record Person ( String name , int age ) {}
if(
new Person( "Carol" , 27 ) // Compiler auto-generates implicitly the constructor.
.equals( // Compiler auto-generates implicitly the `equals` method.
new Person( "Carol" , 42 )
)
) // Returns `false`, as the name matches but the age differs.
{ … }
Details
While your specific problem is solved (using ==
for equality test between int
primitive values), there is an alternative that eliminates the need to write that code.
record
Java 16 brings the record feature.
A record is a brief way to write a class whose main purpose is to transparently and immutably carry data. The compiler implicitly creates the constructor, getters, equals
& hashCode
, and toString
.
equals
method provided automatically
The default implicit equals
method compares each and every member field that you declared for the record. The members can be objects or primitives, both types are automatically compared in the default equals
method.
For example, if you have a Person
record carrying two fields, name
& age
, both of those fields are automatically compared to determine equality between a pair of Person
objects.
public record Person ( String name , int age ) {}
Try it.
Person alice = new Person( "Alice" , 23 ) ;
Person alice2 = new Person( "Alice" , 23 ) ;
Person bob = new Person( "Bob" , 19 ) ;
boolean samePerson1 = alice.equals( alice2 ) ; // true.
boolean samePerson2 = alice.equals( bob ) ; // false.
You can override the equals
method on a record, if you want a behavior other than the default. But if you do override equals
, be sure to override hashCode
for consistent logic, as you would for a conventional Java class. And, think twice: Whenever adding methods to a record
, reconsider if a record structure is really appropriate to that problem domain.
Tip: A record
can be defined within another class, and even locally within a method.