Reputation: 213
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 .
Upvotes: 0
Views: 1796
Reputation: 56059
The immediate problem is that hashCode
needs a capital C
, you are implementing hashcode
with a lowercase c
.
((dog)o).name == name
compares the identities of the strings. That means if you have two instances of the string "GM"
, they will .equals()
each other, but not ==
.
Upvotes: 3