The following is from the Implementation Note section of Java doc of EnumMap :
Implementation note: All basic operations execute in constant time.
They are likely (though not guaranteed) to be faster than their
HashMap counterparts.
I have seen a similar line in the java doc for EnumSet also . I want to know why is it more likely that EnumSets and EnumMaps will be more faster than their hashed counterparts ?
EnumSetis backed by a bit array. Since the number of different items you can put inEnumSetis known in advance, we can simply reserve one bit for each enum value. You can imagine similar optimization forSet<Byte>orSet<Short>, but it’s not feasible forSet<Integer>(you’d need 0.5 GiB of memory for 2^32 bits) or in general.Thus basic operations like
existsoraddar constant time (just likeHashSet) but they simply need to examine or set one bit. NohashCode()computation. This is whyEnumSetis faster. Also more complex operations like union or easily implemented using bit manipulation techniques.In OpenJDK there are two implementations of
EnumSet:RegularEnumSetcapable of handling enum with up to 64 values inlongandJumboEnumSetfor bigger enums (usinglong[]). But it’s just an implementation detail.EnumMapworks on similar principles, but it usesObject[]to store values while key (index) is implicitly inferred fromEnum.ordinal().