I'm writing something which will receive quite a number of transactions per second. For every transaction that comes in, a reference is made to a map which key values are the id and a bean which will help process that particular transaction. Basically each transaction comes in bearing an id, a look up will be done to the map to retrieve the corresponding bean for processing. The sticky part comes with the fact that the id for each transaction is not meant to match the id in the map precisely. More of a begins with operation. To that end, instead of using a string as an id, I've created a simple pojo called MyId. Codes below:
public class MyId
{
private static final int HASHCODE_CONSTANT = 1;
private String value;
public MyId(String value)
{
this.value = value;
}
@Override
public int hashCode()
{
//Returns the same hashcode value for all instances of this pojo
return HASHCODE_CONSTANT;
}
@Override
public boolean equals(Object obj)
{
//Checks for object type, forcibly casts and then compares the starts with
if(obj instanceof MyId)
{
if(!(obj == null || "".equals(obj)))
{
return this.value.startsWith(((MyId)obj).getValue());
}
}
return false;
}
public String getValue()
{
return value;
}
public void setValue(String value)
{
this.value = value;
}
//Test
public static void main(String[] args)
{
Map map = new HashMap();
map.put(new MyId("123456"), "");
System.out.println("Result: " + map.containsKey(new MyId("12345677")));
System.out.println("Result: " + map.containsKey(new MyId("11234567")));
}
}
First test returns true and second test returns false like its supposed to. It seems that the map.containsKey() method invokes and compares your object's hashcode method first before the equals() is ever called. If your hashes don't match, it won't even bother to compare. While this works, it feels a little dodgy having to implement the hashcode method in this manner to trick the map.
Was wondering if there's a more efficient way to do this. We are dealing with quite a number of transactions/second and hence quite a number of look up on the map.
PS: I coded this blind so I'm sure there are syntax errors. Please ignore those. Just trying to convey the general idea.