----------------------------------------------------------------------
Declaration Example 1:
public enum Size { SMALL, MEDIUM, LARGE, EXTRA_LARGE };
----------------------------------------------------------------------
Declaration Example 2:
enum Size
{
SMALL("S"), MEDIUM("M"), LARGE("L"), EXTRA_LARGE("XL");
private Size(String abbreviation) { this.abbreviation = abbreviation; }
public String getAbbreviation() { return abbreviation; }
private String abbreviation;
public static Size getFromAAbbreviation(String abbreviation)
{
for(Size size : Size.values())
if(size.getAbbreviation().equals(abbreviation) return size;
}
}
----------------------------------------------------------------------
How to convert String to an Enum instance?
Size s = (Size) Enum.valueOf(Size.class, "SMALL");
or
Size s = Size.valueOf("SMALL");
----------------------------------------------------------------------
How to enumerate?
Size[] values = Size.values();
----------------------------------------------------------------------
Remember:
1) you never need to use equals for values of enumerated types. Simply use == to compare them. Since The class has exactly four instances—it is not possible to construct new objects.
本文详细介绍了枚举类型的定义方法及使用技巧,包括不同方式创建枚举实例、如何遍历枚举值等,并提供了示例代码。
565

被折叠的 条评论
为什么被折叠?



