I am learning about hashcode()
method in java. I was going through the tutorials
and saw that hashcode() is mainly used in HashMap,HashTable and HashSet.
This is what I have understood,If we want to insert an object as an key, then we have to override hashcode().
Other it wont be able to lookup for the key.
I did a small example and I could achieve this without overriding the hashCode.
So what is the exact use of hashCode() ?
See the code below
package hashcode;
public class Bucket {
private int number;
public void setNumber(int number) {
this.number = number;
}
public int getNumber() {
return number;
}
@Override
public String toString() {
return "" + number;
}
}
package hashcode;
import java.util.Hashtable;
public class MainHashcodeExample {
public static void main(String[] args) {
Hashtable<Bucket, String> map = new Hashtable<>();
Bucket bucket = new Bucket();
bucket.setNumber(100);
map.put(bucket, "A");
System.out.println(map.get(bucket));
}
}