I am having performance problems due to the fact that in order to retrieve the value for some key, I have to check whether each key stored in the map is equal to my test key. The performance problem stems from the fact that I had to override the map's get operation which checks if the map has the test key. I need some kind of tuples for my keys and I use String[]
to store two String
s. Here is my class with a map.
public class ClassWithMap {
Map<String[], Double> arrayToDoubleMap;
public ClassWithMap() {
arrayToDoubleMap = new HashMap<String[], Double>() {
@Override
public Double get(Object key) {
String[] stringArray = (String[]) key;
Set<String[]> keySet = this.keySet();
for (String[] tuple : keySet) {
if (tuple[0].equals(stringArray[0]) && tuple[1].equals(stringArray[1])) {
key = tuple;
break;
}
}
return super.get(key);
}
};
}
public Double getDouble(String string1, String string2) {
String[] tuple = { string1, string2 };
return (Double) arrayToDoubleMap.get(tuple);
}
}
Here is some method for testing.
public static void main(String[] args) {
ClassWithMap map = new ClassWithMap();
String[] tuple1 = { "foo", "bar" };
map.arrayToDoubleMap.put(tuple1, 0.0);
String[] tuple2 = { "fee", "fum" };
map.arrayToDoubleMap.put(tuple2, 1.0);
System.out.println(map.getDouble("fee", "fum"));
}
If I do not override the get
operation in the map declaration, I get null
because the String[]
key is not exactly the same as the test String[]
key.
So my question is: is there a more efficient way to impose this object equivalence than to make a method which checks if there is a match between every key and test key?