Getting HashMap.get to work for the key object

I made a HashMap that uses a simple class Id as the key and a ServerInfo as the value. Id is simple -- just a char and an int, i.e. new Id('A', 1). The problem I'm having is when I use an Id ('A', 1) as a key and associate some ServerInfo object with it, then try to use a different Id with those same values to retrieve the ServerInfo, no entry in the map is found.

I created a Id.equals() which evaluates to true for 2 different ('A', 1) Ids, and also created a Id.hashCode() which returns an int value of the char + the int, so 2 different Ids containing ('A', 1) return the same hash code. And yet get still won't return a stored object.

Anyone know how to get this to work?

If it helps, the code of interest in the Id class is:

publicint hashCode(){

int rv = type + intId;

}

publicboolean equals(Id otherId){

return this.toString().equals(otherId.toString());

}

public String toString(){

returnnew String("" + type + intId);

}

and code used elsewhere to demonstrate this doesn't work:

Id test1 =new Id('A', 1);

servers.put(test1,new ServerInfo(test1));

Id test2 =new Id('A', 1);

si = servers.get(test2);// SI IS NULL instead of new ServerInfo(test1)

[1948 byte] By [zaboomafoozarga] at [2007-11-26 16:43:11]
# 1
Are you using an IdentityHashMap instead of a HashMap? Your implementation looks fine and you should be able to retrieve the object. Try returning a constant (say, 1) from your hashCode method and see what happens.
javafora@gmail.coma at 2007-7-8 23:10:18 > top of Java-index,Core,Core APIs...
# 2

Nope, I was using HashMap. Just figured it out a second ago. The problem was this:

Id.equals(Id otherId) was not overriding the inherited equals, because the inherited equals has an Object parameter. When I changed Id.equals(Id otherId) to Id.equals(Object otherId) the override worked and everything is now functioning as intended.

GOODY!

zaboomafoozarga at 2007-7-8 23:10:18 > top of Java-index,Core,Core APIs...