如何有效地使用Enum对象作为Map数据结构中的键? [英] How to efficiently use Enum objects as keys in the Map data structure?
本文介绍了如何有效地使用Enum对象作为Map数据结构中的键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
解决方案
我学到了一个更有效和专门的Map集合的实现方法这最近在我不小心绊倒了Java API中的答案。如果您有一个使用枚举作为键的地图,请确保使用 EnumMap的。这很简单,而且更有效率:
public interface LibraryItem {...}
public enum LibraryItemType {BOOK,CD,VHS,AUDIO; ...}
Map< LibraryItemType,NavigableSet< LibraryItem>> itemsByType =
new EnumMap<>(LibraryItemType.class);
Is there a more efficient and specialized implementation of a Map collection where Enum objects can serve as keys?
解决方案
I learned this recently after I accidentally stumbled upon the answer in the Java API. If you ever have a map that uses enums as keys make sure you use EnumMap. It's very simple and much more efficient:
public interface LibraryItem{ ... }
public enum LibraryItemType{ BOOK, CD, VHS, AUDIO; ... }
Map<LibraryItemType, NavigableSet<LibraryItem>> itemsByType =
new EnumMap<>(LibraryItemType.class);
这篇关于如何有效地使用Enum对象作为Map数据结构中的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文