我enum在Java类中有以下内容:
public enum Resolution {
RES_32 (32),
RES_64 (64);
private final int asInt;
private Resolution(int asInt) {
this.asInt = asInt;
}
};
Run Code Online (Sandbox Code Playgroud)
我有更多类需要类似的类enum,具有相同的asInt属性和相同的构造函数,但具有不同的常量.所以,在另一个课程中,我需要以下内容enum:
public enum Resolution {
RES_32 (32),
RES_64 (64),
RES_128 (128);
private final int asInt;
private Resolution(int asInt) {
this.asInt = asInt;
}
};
Run Code Online (Sandbox Code Playgroud)
如果这是一个类,我可以使用继承来不重复构造函数中的代码(并且可能会为该asInt属性创建一个getter ).每次我需要这样的时候,我该怎么办才能停止重复自己Resolution enum?理想情况下,我只想为每个常量指定常量Resolution,并保留构造函数和属性.
EnumSet在这方面可能会有所帮助.鉴于以下内容,
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;
}
};
Run Code Online (Sandbox Code Playgroud)
可以使用适当命名的组,如下所示.
for (Resolution r : Resolution.deluxe) {
System.out.println(r.asInt);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1794 次 |
| 最近记录: |