枚举枚举的枚举 [英] Iterating enum of enums

查看:110
本文介绍了枚举枚举的枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public class EnumTest {
enum fauna
{
动物,鸟类;

enum动物
{
虎(虎),
狮子(狮子);

字符串名称;

动物(字符串名称)
{
this.name = name;
}
}

枚举鸟
{
孔雀(孔雀),
owl(猫头鹰);

字符串名称;

鸟(字符串名)
{
this.name = name;
}
}
}
}

我找不到一种迭代枚举动物群来打印枚举动物和鸟类的名字的方法。有什么办法吗?

解决方案

不幸的是,您无法对这样的枚举进行分组。枚举鸟类动物群鸟类值不同>枚举。通常的方法是添加一个也是枚举的字段:

 枚举动态(
枚举类型) {MAMMAL,BIRD}

TIGER(Type.MAMMAL),
LION(Type.MAMMAL),
PEACOCK(Type.BIRD),
OWL(Type。鸟);

private final类型类型;

动物(类型){this.type = type; }

}

如果您只想要特定类型的动物,例如,所有 BIRD s,您将不得不编写一个帮助方法来执行此操作,迭代所有动物群值并挑选正确类型的。 (除非你运行Java 8,在这种情况下它只是 Stream.of(Fauna.values())。filter(f - > f.type == BIRD).toList() code>或类似的东西)。


I have a structure some-thing like

public class EnumTest{
     enum fauna
     {
         Animals, Birds;

         enum Animals
         {
              Tiger("tiger"),
              Lion("lion");

              String name;

              Animals(String name)
              {
                   this.name = name; 
              }
         }

         enum Birds
         {
              Peacock("peacock"),
              owl("Owl");

              String name;

              Birds(String name)
              {
                   this.name = name; 
              }
         }
     }
}

Now I couldn't find a way to iterate over the enum fauna to print the names of enum animals and birds. Is there any way to do it??

解决方案

Unfortunately, you can't group enums like this. The enum Birds is distinct from the Birds value inside the fauna enum. The usual way to do it is to add a field which is also an enum:

enum Fauna {
    enum Type { MAMMAL, BIRD }

    TIGER(Type.MAMMAL), 
    LION(Type.MAMMAL), 
    PEACOCK(Type.BIRD), 
    OWL(Type.BIRD);

    private final Type type;

    Fauna(Type type) { this.type = type; }

}

If you only want the animals of a specific type, for example all BIRDs, you will unfortunately have to write a helper method to do that, iterating over all the Fauna values and picking those of the correct type. (Unless you're running Java 8, in which case it's just Stream.of(Fauna.values()).filter(f -> f.type == BIRD).toList() or something similar).

这篇关于枚举枚举的枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆