I am trying the below piece of code.
class dog{
private String name;
public dog(String n){
name = n;
}
public String getname(){ return name; }
public void setname(String n){ name =n;}
public boolean equals(Object o){
//if (( o instanceof dog )&& (((dog)o).name == name)) return true;
if (( o instanceof dog )&& (((dog)o).name.equals(name))) return true;
else return false;
}
public int hashcode(){
return name.length();
}
public String toString(){
return "Name:"+name;
}
}
This is my Dog class . Now in Main method , I am trying to do the following
Map<Object,Object> m = new HashMap <Object, Object>();
dog p = new dog("GM");
dog q = new dog ("GM");
System.out.println(p.equals(q));
m.put ( new dog("GM"),"K2");
System.out.println(m.get(new dog("GM")));
I am getting a true and a null value. i Was expecting a K2 instead of null . Can somebody help me with this . I have overridden hashcode and equals methods . What is the thing i am missing ??
EDIT : - Changed equals function. Same results .
name.hashCode()instead ofname.length(), you are using one of the worsts hash functions you can. It won't return negatives, and it rarely uses large numbers.Dognotdog2- rename the getter and setter methods togetNameandsetNameso you (and most of libraries) can access them using interpspection.