3

I have a record like:

record Data(int x, int y, int a) {}

It gets default equals and hashCode methods.


How could I adjust those methods to have custom behavior? Lets say, I want to ignore a in the methods.

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
Thirumal
  • 8,280
  • 11
  • 53
  • 103

1 Answers1

1

Unfortunately, there is only one way to do this: You have to implement the methods yourself. Just overwrite these methods like you would do it with all other classes, too. In your own implementation, only use the properties you want. Your IDE usually helps you implement standard code and asks for the properties which should be included.

Alternatively, you can use tools like Lombok with annotations instead of implementation:

@Data
public class Data{
    private int x;
    private int y;
    @EqualsAndHashCode.Exclude private int a;
}
McPringle
  • 1,939
  • 2
  • 16
  • 19
  • Could you elaborate a bit, maybe add the final code in your answer? I.e. spend some effort writing a good quality answer? (see [answer]) – Zabuzard Nov 18 '21 at 09:39
  • Lombok's `@EqualsAndHashCode` does not support records, only classes. I've created a feature request to change it, feel free to like/comment: https://github.com/projectlombok/lombok/issues/3246 – Paweł Aug 15 '22 at 11:15