gpt4 book ai didi

java - 由 EnumMap/EnumSet 完成的优化

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:40:10 28 4
gpt4 key购买 nike

我最近读了一篇关于 EnumMap 的文章.上面写道“使用 EnumMap 带来了针对枚举键的特定实现的好处,简而言之,EnumMap 专门针对枚举键优化了 Map 实现。”

还写到“枚举是使用数组实现的,常见操作的结果在恒定时间内。因此,如果您正在考虑高性能MapEnumMap 可能是枚举数据的不错选择。”


有人可以指出这些优化是如何完成的吗? ( “操作结果在常数时间内”)

最佳答案

查看 documentation for EnumMap :

A specialized Map implementation for use with enum type keys. All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created. Enum maps are represented internally as arrays. This representation is extremely compact and efficient.

Enum maps are maintained in the natural order of their keys (the order in which the enum constants are declared). This is reflected in the iterators returned by the collections views (keySet(), entrySet(), and values()).

简而言之,一个 EnumMap只是一个数组,属于 map 值的类型。换句话说,一个 EnumMap<SomeEnum, SomeValue> , 将只是一个 SomeValue[] .

您可能会问,索引是如何分配的?它们按枚举的自然顺序分配。示例:

enum Day {
MON, TUE, WED, THU, FRI, SAT, SUN
}

上述枚举具有以下自然顺序。

MON TUE WED THU FRI SAT SUN
0 1 2 3 4 5 6

因此,类似 map.put(Day.FRI, "Yay!") 的操作实际上可以看作:

array[4] = "Yay!";

数组访问是一个常量时间操作,这就是为什么 EnumMap它的好处也是如此。查找 ( get()) 的工作方式相同。

关于java - 由 EnumMap/EnumSet 完成的优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16637288/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com