假設你有如何獲取枚舉的數值?
public enum Week {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
一個如何得到int
表示週日是0,週三是3等?
假設你有如何獲取枚舉的數值?
public enum Week {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
一個如何得到int
表示週日是0,週三是3等?
Week week = Week.SUNDAY;
int i = week.ordinal();
但要小心,如果您在聲明中更改枚舉常量的順序,該值將會改變。解決此獲得的一種方式是一個int值自分配給您的所有枚舉常數是這樣的:
public enum Week
{
SUNDAY(0),
MONDAY(1)
private static final Map<Integer,Week> lookup
= new HashMap<Integer,Week>();
static {
for(Week w : EnumSet.allOf(Week.class))
lookup.put(w.getCode(), w);
}
private int code;
private Week(int code) {
this.code = code;
}
public int getCode() { return code; }
public static Week get(int code) {
return lookup.get(code);
}
}
您可以撥打:
MONDAY.ordinal()
,但我個人的屬性添加到enum
存儲該值,將其初始化爲enum
構造函數並添加一個函數以獲取該值。這樣更好,因爲如果enum
常量被移動,則MONDAY.ordinal
的值可能會更改。
Take a look at the API它通常是一個體面的地方開始。雖然我不會猜到沒有遇到過這個問題之前,你打電話給ENUM_NAME.ordinal()
是的,只需使用序號枚舉對象的方法。
public class Gtry {
enum TestA {
A1, A2, A3
}
public static void main(String[] args) {
System.out.println(TestA.A2.ordinal());
System.out.println(TestA.A1.ordinal());
System.out.println(TestA.A3.ordinal());
}
}
API:
/**
* Returns the ordinal of this enumeration constant (its position
* in its enum declaration, where the initial constant is assigned
* an ordinal of zero).
*
* Most programmers will have no use for this method. It is
* designed for use by sophisticated enum-based data structures, such
* as {@link java.util.EnumSet} and {@link java.util.EnumMap}.
*
* @return the ordinal of this enumeration constant
*/
public final int ordinal() {
return ordinal;
}
5年晚,不比任何一個以前的答案 – Trilarion 2018-01-03 20:43:28
@Trilarion的,現在你已經5年多了,你有更好的答案嗎? ;) – 2018-01-04 04:55:09
+1提供一個很好的答案,其中有1襯墊就已經足夠了 – avalancha 2013-12-02 09:07:22