java枚举类的值,具有多个值类型的Java枚举

博客讨论了如何改进枚举类的设计,建议将每个枚举实例的属性用单独的变量表示,而非使用数组。通过创建带有构造函数的枚举,可以更清晰地定义和访问每个州的全名、缩写和是否为原始殖民地等信息。这种方法遵循了更好的命名规范和代码组织原则。
摘要由CSDN通过智能技术生成

Basically what I've done is write an enum for States, and I want to not only be able to access them just as states but also access their abbreviation and whether or not they were an original colony.

public enum States {

...

MASSACHUSETTS("Massachusetts", "MA", true),

MICHIGAN("Michigan", "MI", false),

...; //so on and so forth for all fifty states

private final Object[] values;

States(Object... vals) {

values = vals;

}

public String FULL() {

return (String) values[0];

}

public String ABBR() {

return (String) values[1];

}

public boolean ORIGINAL_COLONY(){

return (boolean) values[2];

}

}

This seems to work as I'd expect it to. I can

System.out.println(States.ALABAMA); // Prints "ALABAMA"

System.out.println(States.ALABAMA.FULL()); // Prints "Alabama"

System.out.println(States.ALABAMA.ABBR()); // Prints "AL"

System.out.println(States.ALABAMA.ORIGINAL_COLONY());// Prints "false"

For this particular scenario involving enums, is this the best way to do this or is there a better way to setup and format this enum? Thanks to all in advance!

解决方案

First, the enum methods shouldn't be in all caps. They are methods just like other methods, with the same naming convention.

Second, what you are doing is not the best possible way to set up your enum. Instead of using an array of values for the values, you should use separate variables for each value. You can then implement the constructor like you would any other class.

Here's how you should do it with all the suggestions above:

public enum States {

...

MASSACHUSETTS("Massachusetts", "MA", true),

MICHIGAN ("Michigan", "MI", false),

...; // all 50 of those

private final String full;

private final String abbr;

private final boolean originalColony;

private States(String full, String abbr, boolean originalColony) {

this.full = full;

this.abbr = abbr;

this.originalColony = originalColony;

}

public String getFullName() {

return full;

}

public String getAbbreviatedName() {

return abbr;

}

public boolean isOriginalColony(){

return originalColony;

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值