在 Java 中使用枚举的正确且最常见的方法是什么?
假设我需要在类构造函数或工厂方法参数中使用枚举,我能想到的第一件事就是包含 public static enum
在我的类(class)中,然后导入它。
package mypackage;
import mypackage.Data.ContentType;
class Data {
public static enum ContentType { TYPE1, TYPE2, TYPE3 }
ContentType type;
String value;
public Data( String value, ContentType type ) {
this.value = value;
this.type = type;
}
}
用法示例:new Data( "some value", ContentType.TYPE1 );
.
人们更喜欢使用如下结构的原因是什么?
public static final int TYPE1 = 1;
public static final int TYPE2 = 2;
public static final int TYPE3 = 3;
最佳答案
我犹豫是否称其为“常见”用法,但枚举非常适合创建 some kinds of state machines .
关于java - Java 中枚举最常见的用法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18317600/