The naive implementation for your requirement would look like this:
record MyRecord( int a, int b )
{
int hash; // Does not compile!!
MyRecord
{
hash = a * 100 + b;
}
@Override
public int hashCode() { return hash; }
}
When compiling that, JShell tells you:
| Error:
| field declaration must be static
| (consider replacing field with record component)
| int hash;
| ^---^
Presumably, the error message returned by javac
would look slightly different, but with more or less the same meaning: a record
cannot have additional attributes other than the record components. And that would lead to a construct as shown in this answer.
If the hashcode calculation is really, really, REALLY time consuming, you can consider something like this:
record MyRecord( int a, int b )
{
static final Map<MyRecord,Integer> hashes = new IdentityHashMap<>();
public MyRecord
{
hashes.put( this, a * 100 + b );
}
@Override
public int hashCode() { return hashes.get( this );}
}
But as this simple implementation is causing significant memory dissipation, you need to implement also a cleanup for the hashes
map; otherwise an OutOfMemoryError
will be thrown at some time …
A comment for the downvote would be appreciated.