Let's say I have an enum like the following:
public enum Utils {
UTIL_1, UTIL_2, ... UTIL_n
}
Now, I have Set<Utils> myUtils
, which contains a bunch of these enum entries. Some other module (on which I don't have any control) gives me one such util name (say "UTIL_i
") as a String. I need to check if it is contained in the set myUtils
. Is there any way to perform this operation in O(1)? I understand, I could change the set to be a set of Strings, and then do a .contains() on that, but I want to keep it as a last resort.
Update:
Following the suggestions in the answer, I tried a little experiment. I created a small code snippet to generate a java file which contains an enum of a fixed size. I tried with size 1000, 2500, 5000. An enum of size 10000 showed me the error The code for the static initializer is exceeding the 65535 bytes limit
in Eclipse, which is explained here. I created a Set myUtils
and pushed all the elements from the Enum to that set. For each of these different size myUtils
I executed a snippet 1000 times, which looks like myUtils.contains(Utils.valueOf(<elementName>))
. The average execution time of that code snippet in ms is given below:
Enum size=1000
UTIL_1 search duration = 1704ms
UTIL_500 search duration = 2316ms
UTIL_1000 search duration = 1732ms
Enum size=2500
UTIL_1 search duration = 2326ms
UTIL_1250 search duration = 1886ms
UTIL_2500 search duration = 1860ms
Enum size=5000
UTIL_1 search duration = 2569ms
UTIL_2500 search duration = 2709ms
UTIL_5000 search duration = 2361ms
It clearly shows the average execution time of Enum.valueOf(String element)
increases with the size of the enum, but I'm not sure of the time complexity of this method.