I have a class that gives details about payment.The attributes are
accountNo, transactionAmount, dateOfTransaction.
Here I want to write hash function such that it will efficient when I开发者_如何学C store this class objects in a hashSet.
The main constraint is payment details should be unique(suppose a particular person should not pay fee two times in a month).
Can any one help me in hashCode to be written for this scenario and also equals method?
You need to decide exactly what you mean by equality. In particular, you talk about not paying twice in a month - does that mean one transaction should be equal to another if it's in the same month even if it's on a different day? That sounds like quite an odd - and very usage-specific rather than type-specific - idea of equality. Also note that the transaction only has one account number - surely it should have both a "from" and a "to" account, as there could be payments from multiple people to the same account, and there could be payments from one account to multiple accounts in the same month.
So, personally I wouldn't want to override equality in this way, but if you really do have to, it's not too hard... Once you've decided on what consitutes equality, I would implement equals
- at that point hashCode
is usually fairly easy.
I would strongly recommend that you read Josh Bloch's section on equality in Effective Java (second edition) for more details, but equals
would typically look something like this:
@Override public boolean equals(Object other)
{
if (other == null || other.getClass() != this.getClass())
{
return false;
}
BankTransaction otherTransaction = (BankTransaction) other;
return accountNo == otherTransaction.accountNo
&& transactionAmount == otherTransaction.transactionAmount
&& // etc;
}
Note that for any field which is a reference type, you need to determine what sort of equality you want to apply there - often you'll want to call equals
instead of just using the reference comparison provided by ==
.
I suggest you use the hashcodebuilder of the apache commons package:
http://commons.apache.org/lang/api-2.6/org/apache/commons/lang/builder/HashCodeBuilder
There is also an EqualsBuilder:
http://commons.apache.org/lang/api-2.6/org/apache/commons/lang/builder/EqualsBuilder
If you implememt both you should not worry about storing your objects in a hashset
The definitive answer to this question is in Effective Java (second edition).
精彩评论