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.
return 1- but that is next to useless as your class wouldn't work inHashMaps andHashSets. What are you using thisequalsmethod for?equalsandhashCodealone and create a method that checks this. The reason to override those methods is so thatCollections respect equality using yourequalsmethod rather than the default which uses==.Schoolobject 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.