【发布时间】:2018-08-01 10:32:10
【问题描述】:
假设我有一个像下面这样的枚举:
public enum Utils {
UTIL_1, UTIL_2, ... UTIL_n
}
现在,我有Set<Utils> myUtils,其中包含一堆这些枚举条目。其他一些模块(我没有任何控制权)给我一个这样的实用程序名称(比如“UTIL_i”)作为字符串。我需要检查它是否包含在集合myUtils 中。有没有办法在 O(1) 中执行此操作?我了解,我可以将集合更改为一组字符串,然后对其执行 .contains(),但我想保留它作为最后的手段。
更新:
按照答案中的建议,我尝试了一个小实验。我创建了一个小代码 sn-p 来生成一个包含固定大小枚举的 java 文件。我尝试使用大小 1000、2500、5000。大小为 10000 的枚举向我显示了 Eclipse 中的错误 The code for the static initializer is exceeding the 65535 bytes limit,对此进行了解释 here。我创建了一个 Set myUtils 并将 Enum 中的所有元素推送到该集合。对于这些不同大小的myUtils,我执行了 1000 次 sn-p,看起来像 myUtils.contains(Utils.valueOf(<elementName>))。该代码 sn-p 的平均执行时间(以 ms 为单位)如下所示:
枚举大小=1000
UTIL_1 search duration = 1704ms
UTIL_500 search duration = 2316ms
UTIL_1000 search duration = 1732ms
枚举大小=2500
UTIL_1 search duration = 2326ms
UTIL_1250 search duration = 1886ms
UTIL_2500 search duration = 1860ms
枚举大小=5000
UTIL_1 search duration = 2569ms
UTIL_2500 search duration = 2709ms
UTIL_5000 search duration = 2361ms
它清楚地显示了Enum.valueOf(String element) 的平均执行时间随着枚举的大小而增加,但我不确定这个方法的时间复杂度。
【问题讨论】: