kpachopoulos |
04-15-2007 12:54 PM |
java: java.util.Hashmap doesn't work for a custom object
Hi,
i have created a class named ID. I am trying to test it on a Hashmap, but the the "containsKey" and "get" operations do not work. Every operation of the main method returns as if the ID objects have not been inserted. Ideas?
Code:
package swarm.sys.id;
import java.util.*;
import java.io.*;
import swarm.sys.common.*;
import swarm.sys.interfaces.*;
public class ID implements IDInterface, Cloneable, Serializable
{
String type;
int body;
String id;
private static int idCounter=0;
public ID(String type, int body)
{
this.type=type;
this.body=body;
id=type+Ids.padWithZeroes(body);
}
public String getType()
{
return type;
}//getType
public String getBody()
{
return Ids.padWithZeroes(body);
}//getBody
public int getIntBody()
{
return body;
}//getIntBody
public boolean equals(Object o)
{
if (!(o instanceof ID))
{
return false;
}
else
{
ID id=(ID)o;
return (type.equals(id.getType()) && (body==id.getIntBody()));
}
}//equals
/* factory method, which produces new IDs and afterwards
* increments the body part
*/
public static ID newID(String type)
{
return new ID(type,idCounter++);
}//newID
//implements deep cloning
public Object clone()
{
return new ID(new String(this.type),this.body);
}//clone
public String toString()
{
return id.trim();
}//toString
public static void main(String[] args)
{
Hashtable<IDInterface,String> table=new Hashtable<IDInterface,String>();
table.put(new ID("PEER_",1),"x1");
table.put(new ID("PEER_",2),"x1");
table.put(new ID("PEER_",3),"x2");
table.put(new ID("PEER_",4),"x3");
table.put(new ID("PEER_",5),"x3");
ID id1=new ID("PEER_",1);
ID id14=new ID("PEER_",14);
System.out.println("table.containsKey(new ID(PEER_,1)): "+table.containsKey(id1)); //should be true
System.out.println("table.containsKey(new ID(PEER_,14)): "+table.containsKey(id14)); //should be false
System.out.println("table.get(new ID(PEER_,1))"+table.get(id1)); //should be x1
}
|