A
andrew.tanenbaum
Hi, I have a problem with a HashMap. I store a couple key-value of type
MyClass-Integer, but when I try to get the value, it returns null, even
if the keys seem equal. For example, suppose that MyClass has an
attribute called "name", which value is passed in the constructor, if I
do something like:
MyClass obj1 = new MyClass("MyName");
myHashMap.put(obj1, 1);
MyClass obj2 = new MyClass("MyName");
Integer value = myHashMap.get(obj2);
It should return something, and not null.
My question is, how a hashmap verifies if it contains the key "obj2"? I
suppose that it invokes the method "equals" of the class MyClass. So,
if I redefine the "equals" method in this way
public boolean equals(Object o){
if(o instanceof MyClass)
return name.equals(((MyClass)o).getName())
else
return super.equals(o);
}
it should works? Or not?
Thanks
MyClass-Integer, but when I try to get the value, it returns null, even
if the keys seem equal. For example, suppose that MyClass has an
attribute called "name", which value is passed in the constructor, if I
do something like:
MyClass obj1 = new MyClass("MyName");
myHashMap.put(obj1, 1);
MyClass obj2 = new MyClass("MyName");
Integer value = myHashMap.get(obj2);
It should return something, and not null.
My question is, how a hashmap verifies if it contains the key "obj2"? I
suppose that it invokes the method "equals" of the class MyClass. So,
if I redefine the "equals" method in this way
public boolean equals(Object o){
if(o instanceof MyClass)
return name.equals(((MyClass)o).getName())
else
return super.equals(o);
}
it should works? Or not?
Thanks