-1

I am using a class i made named Key. It has 2 fields:

  1. address (type MyAddress) that have a GUID (type long)
  2. id (type long)

This class can have at any given point one of the following:

  • address is not null and id==-1
  • adresss is null and id > 0

Will it be correct to do the following:

int hashcode(){
  if (address==null) return Long.hashCode(id)
  else return Long.hashcode(address.guid)
}

Is there any problem that might occur from that? I mainly want to make sure that this is the right way to make a hashcode in this union-like class when only one of the fields is relevant in any given time.

slashms
  • 928
  • 9
  • 26

1 Answers1

0

The requirement of a hash code is that two equal objects have the same hash code. It looks like your hash code meets this, and is thus perfectly valid.

That said, it's better practice to combine all of the fields that your equals method is testing, and to design the hash code in such a way that, should this object be used in a HashSet, the objects are spread reasonably evenly throughout. This answer will outline a good example on how to do this.

Community
  • 1
  • 1
Joe C
  • 15,324
  • 8
  • 38
  • 50