java 枚举嵌套枚举,在Java中嵌套枚举

I want to nest some enums. The object i'm representing are Flags, with a type, and a value. There are a discrete number of types, and each type has a distinct set of possible values.

So if Type A can have values 1, 2 or 3, and Type B can have values 4,5,6, I'd like to be able to do things like:

Flag f = Flag.A.1;

f.getType() - returns "A"

f.getValue() - returns "1"

Flag f2 = Flag.A.4; -- Syntax error.

I'm driving myself crazy trying to nest enums within enums - is what i'm trying possible - do I need to ditch enums altogether and handcraft a static class with static members?

My best effort so far is:

public class Flag {

enum A extends Flag {

ONE("ONE"),

TWO("TWO"),

THREE("THREE");

private A(String value) {

Flag.type = "A";

Flag.value = value;

}

}

private static String type;

private static String value;

}

But if I do:

Flag f = Flag.A.ONE;

The types are incompatible.

解决方案

You cannot have a number as an enum. It has to be an identifier.

You can do this

interface Flag {

String getType();

int getValue();

enum A implements Flag{

one, two, three;

String getType() { return getClass().getSimpleName(); }

int getvalue() { return ordinal()+1; }

}

enum B implements Flag{

four, five, six;

String getType() { return getClass().getSimpleName(); }

int getvalue() { return ordinal()+4; }

}

}

Flag f = Flag.A.one;

However a simpler option may be

enum Flag {

A1, A2, A3, B4, B5, B6;

public String getType() { return name().substring(0,1); }

public int getValue() { return name().charAt(1) - '0'; }

}

Flag f = Flag.A1;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值