具有多个值类型的Java枚举 [英] Java enum with multiple value types

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

问题描述

基本上我所做的是为国家编写一个枚举,我不仅要能够访​​问它们,而且可以访问它们的缩写,以及它们是否是原始殖民地。

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;
    }
}

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

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