I am struggling to write proper hashCode function for the Student class given below.
1) What I believe that hashCode should be good enough so that two different object's hashCode should not collide with each other.
Observation : For this implementation, when I debugged and checked for 'internal table object of HashMap' class I found each entry in HashMap is assigned different bucket location.
Question : What is the purpose of having a bucket(list/tree) at each index.
Implementation :
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
2) If I allow collision of hashCode:
Observation : For this implementation, when I debugged and checked, found that 'size of internal table of hashMap' keeps increasing and only buckets within the range of hashCode gets used. Rest all bucket indexes shows null.
Question : What is the purpose of increasing internal table size, if the buckets out of hashCode range are always null.
Implementation :
@Override
public int hashCode() {
return id%20;
}
Need Help for proper hashCode Implementation, so that Above issues can be fixed. Thanks for the help in advance.
============================ Code ===========================
public class HashMapTest {
public static void main(String a[]) {
HashMap<Student, Integer> set = new HashMap<Student, Integer>();
for (int i = 0; i < 5000; i++) {
set.put(new Student(i), i);
}
set.put(new Student(5001), 5001);
System.out.println(set.size());
}
}
class Student {
private int id;
public Student(int id) {
this.id = id;
}
// Add here hashCode() provided in comments.
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (id != other.id)
return false;
return true;
}
}