停止Java枚举中的重复 [英] Stopping repetition in Java enums

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

问题描述

我在Java类中有以下枚举

I have the following enum in a Java class:

public enum Resolution {
    RES_32 (32),
    RES_64 (64);
    private final int asInt;
    private Resolution(int asInt) {
        this.asInt = asInt;
    }
};

我有更多类需要类似的枚举,具有相同的 asInt 属性和相同的构造函数,但具有不同的常量。所以,在另一个类中,我需要以下枚举

I have more classes that need a similar kind of enum, with the same asInt property and the same constructor, but with different constants. So, in another class, I need the following enum:

public enum Resolution {
    RES_32 (32),
    RES_64 (64),
    RES_128 (128);
    private final int asInt;
    private Resolution(int asInt) {
        this.asInt = asInt;
    }
};

如果这是一个类,我可以使用继承来重复构造函数中的代码可能已经为 asInt 属性设置了一个getter。每次需要这样一个解决方案时,我可以做些什么来停止重复? 枚举?理想情况下,我想为每个分辨率指定常量,并保留构造函数和属性。

If this was a class, I could use inheritance to not repeat the code in the constructor (and would likely have made a getter for that asInt property). What can I do in order to stop repeating myself each time I need such a Resolution enum? Ideally, I would like to just specify the constants for each Resolution, and to have the constructor and property kept.

推荐答案

EnumSet 可能在此上下文中有所帮助。给出以下内容,

EnumSet may be helpful in this context. Given the following,

public enum Resolution {

    RES_32(32),
    RES_64(64),
    RES_128(128),
    RES_256(256);

    public static Set<Resolution> deluxe = EnumSet.allOf(Resolution.class);
    public static Set<Resolution> typical = EnumSet.range(RES_64, RES_128);
    public static Set<Resolution> ecomomy = EnumSet.of(RES_32);

    private final int asInt;

    private Resolution(int asInt) {
        this.asInt = asInt;
    }
};

可以使用合适的命名集,如下所示。

Suitably named sets may be used as shown below.

for (Resolution r : Resolution.deluxe) {
    System.out.println(r.asInt);
}

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

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