I've never had occasion to write a hashcode function in Java but now I have a need to do so. How do I go about it?
It's for an ArrayList and each element contains 5 Strings and nothing else.
I found an example for an ArrayList that contains 2 string and it's very simple:
return 31 * lastName.hashCode() + firstName.hashCode();
Can I get away with something equally simple, namely:
return 31 * field1.hashcode() + field2.hashcode() + field3.hashcode() + field4.hashcode() + field5.hashcode();
Or does a hashcode() method have further requirements?
I found another StackOverflow discussion of hashcode() here: Best implementation for hashCode method
From that, I imitated one of the answers and came up with this:
return Objects.hash(this.mClientCode, this.mOrderNumber, this.mOrderDate, this.mTicketsSold, this.mSellerName);
Is that better than the first one I suggested? Why?
Since hashcode() and equals() should apparently always get changed at the same time, this is my equals():
public boolean equals(Object o) {
if (!(o instanceof SalesItem)) {
return false;
}
SalesItem n = (SalesItem) o;
return n.mClientCode.equals(mClientCode) && n.mOrderNumber.equals(mOrderNumber) &&
n.mOrderDate.equals(mOrderDate) && n.mTicketsSold.equals(mTicketsSold) &&
n.mSellerName.equals(mSellerName);
}
Does that look okay?