映射中的 Java 枚举用法



所以我正在做一个项目,得到了五个不同的类:

public class Article { ... } 
public class Shirt extends Article { ... } 
public class Boots extends Article { ... } 
...

我可以做类似的事情吗

public enum Articletype {
    Shirt, Boots, ...
}

并在地图中使用这些枚举,例如

Map<Integer,Articletype> testMap = new HashMap<Integer,Articletype>();

我该如何处理?

我已经有一张地图,它保存了"衬衫"-对象,例如

Map<Integer,Shirt> shirts = new HashMap<>()

我尝试了类似的东西

Map<Integer,Articletype> testMap = new HashMap<Integer,Articletype>();
testMap.put(1,shirts.get(1001));

但这行不通。我不认为我完全理解这些枚举类型,但我知道你可以像这样使用这些(或者我错了?

无论如何,我有点想更频繁地利用它们,我希望有人能为这种黑暗带来一些光明。

你可以使用这样的枚举 - 这意味着你基本上用更具表现力的 enum IIUC 替换当前的 int 表示类型,但请注意,它确实有一个缺点,即在添加新文章类型时不太灵活。在这种情况下使用是否是一个好主意,这确实引出了一个问题。

然后,您可以做的是维护一个包含给定类型所有文章的Map<ArticleType, List<Article>>,例如

List<Article> allArticles = ...
Map<ArticleType, List<Article>> grouped = new HashMap<ArticleType,List<Article>>();
for (Article a : allArticles) {
    List<Article> ofType = grouped.computeIfAbsent(a.getArticleType(), ArrayList::new);
    ofType.add(a);
}
// and then you get all shirts by
List<Article> shirts = grouped.get(ArticleType.Shirt);

请注意,在Java 8中,这可以使用流完成更短的时间

Map<ArticleType,List<Article>> bytype = allArticles.stream()
    .collect(Collectors.groupBy(Article::getType));

在您的testMap上下文中没有枚举的位置。要存储在映射中的是扩展 Article 类型的对象。使用Map<Integer, Articletype>没有意义,因为您不是将项目类型映射到整数,而是将文章映射到整数。


例如

,如果您必须按类型对所有文章进行分组,则使用枚举将有一个有效的案例:

Map<ArticleType, List<? extends Article>> articlesByType = new HashMap<>();
List<Boot> bootList = ...
articlesByType.put(ArticleType.BOOT, bootList);

最新更新