I have a class School:
public class School{
private int noOfTeachers;
private int noOfStudents;
//setters and getters....
public boolean equals(Object that){
//instance of check..
return (this.noOfTeachers == ((School)that).noOfTeachers ||
this.noOfStudents== ((School)that).noOfStudents);
}
public int hashCode(){
//What goes in here??? o.O
}
}
How should I proceed with implementation of hashCode
for this class? I am not able to think of a strategy which will involve both noOfTeachers
and noOfStudents
for calculation of hash. Rather noOfTeachers
and noOfStudents
combination seems to be breaching contract between equals
and hashCode
.
1 Answer 1
You will not find any proper hashCode()
implementation for your class, That would serve your need! Because your equals
method uses OR
to its properties of your class. Using OR
in the equals
method returns true
for more than one state of any object.
So using unique return value of the hashCode()
you certainly cannot represent multiple state! And more over you should know, hashCode()
must return unique value for an object.
As returning multiple values by it, leads to an ambiguity (and harms certainty) to put an object into any map. Because that is a violation of the assumption of "Uniqueness of keys of a map".
-
2This certainly doesn't work. The OP wants an
equals
method with an or.Boris the Spider– Boris the Spider2013年05月11日 18:26:03 +00:00Commented May 11, 2013 at 18:26 -
if two objects are equal according to the
equals
method, then calling the hashCode method on each of the two objects must produce the same resultAnirudha– Anirudha2013年05月11日 18:33:33 +00:00Commented May 11, 2013 at 18:33 -
@BoristheSpider, I request you to see the answer now, again, thanks!Sazzadur Rahaman– Sazzadur Rahaman2013年05月11日 18:48:26 +00:00Commented May 11, 2013 at 18:48
return 1
- but that is next to useless as your class wouldn't work inHashMap
s andHashSet
s. What are you using thisequals
method for?equals
andhashCode
alone and create a method that checks this. The reason to override those methods is so thatCollection
s respect equality using yourequals
method rather than the default which uses==
.School
object to be equal to another one? I see you're returning true if either his number of Teachers or number of Students are the same, is this correct? I would think of an object to be equal to another if all of their fields are the same, not only one of them. The easiest way I see to solve this is to implement an own version ofequals(School that)
, which do the comparision between them and forget about overriding the equals and hashCode methods.