gpt4 book ai didi

java - Java 中枚举最常见的用法是什么?

转载 作者:行者123 更新时间:2023-12-01 17:21:41 25 4
gpt4 key购买 nike

在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com