I am trying a test with hashmap for a custom class with overridden equals and hashcode method:
public class Car {
public int hashcode() {
return 1;
}
@Override
public boolean equals(Object o1) {
return true;
}
}
Main Class:
public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap<Car,String> map = new HashMap<Car,String>();
Car c1 = new Car();
Car c2 = new Car();
System.out.println(c2.equals(c1));
System.out.println(c1==c2);
map.put(c1, "car1");
map.put(c2, "car2");
System.out.println(map.size());
System.out.println(map.get(c1));
}
I expected the output as 1 and car2 but it's 2 and car1. Can anyone explain reason. My Equals is true for each car object and hashcode is also same.
Thanks,
It was a typo.hashcode is not overridden.I created a method hashcode() instead of hashCode(). Correcting that provided the expected result.