I am having difficulty comparing the two. So I am appealing to people with more detailed knowledge than me. I have to link a functional object to a name (String ... of course), and the function call is something like this:
serviceInstance.useThis(String name, Object parameter);
So far I am considering three options for the "backend" of this API:
- enum + EnumMap
- pure enum
- HashMap
1 and 2 are basically the same but 1 is in case I need to reuse the enum for other uses. My main concern boils down to how fast is the Enum.valueOf(String name) compared to the String.hashCode()?
here are the two implementations I am playing with:
public class HashMapHandlerType{
static HashMap<String, MyInterfaceProvider> handlers = ~ ;
public void useThis(String name, Object parameter) throws IllegalArgumentException {
MyInterfaceProvider prov = handlers.get(name);
if(prov != null){
prov.get().use(parameter);
}else{
throw new IllegalArgumentException(name);
}
}
}
public class EnumTypeHandler{
public void useThis(String name, Object parameter) throws IllegalArgumentException {
HandlersEnum.valueOf(name).get().use(parameter);
}
}
Advantages of Enum is not worrying about collisions in EnumMap if I wanted to use one. But is valueOf of Enum fast enough to win over String.hashCode() + dealing potential collisions in the hash function?
Enum.valueOfis going to delegate to aHashMapon the backend anyway.