java 使用 enum(列舉)
阿新 • • 發佈:2022-05-20
列舉的使用
- 列舉類的理解:類的物件只有有限個,確定的。我們稱此類為列舉類
- 當需要定義一組常量時,強烈建議使用列舉類
- 如果列舉類中只有一個物件,則可以作為單例模式的實現方式。
列舉的屬性
- 列舉類物件的屬性不應允許被改動,所以應該使用 private final 修飾
- 列舉類的使用 private final 修飾的屬性應該在構造器中為其賦值
- 若列舉類顯式的定義了帶引數的構造器,則在列出列舉值時也必須對應的傳入引數
測試
package com.test; /** * @author z */ public class Test { public static void main(String[] args) { // code System.out.println(MyEnums.MY_TEST_ONE.getCode()); // value System.out.println(MyEnums.MY_TEST_ONE.getValue()); // 獲取變數名列表 for(MyEnums myEnums:MyEnums.getVariables()){ System.out.println(myEnums.toString()); } // 根據 key 獲取 value System.out.println(MyEnums.getValue(2)); } } public enum MyEnums{ MY_TEST_ONE(1,"測試1"), MY_TEST_TWO(2,"測試2"), MY_TEST_three(3,"測試3"), ; private final int code; private final String value; MyEnums(int code,String value){ this.code=code; this.value=value; } /** * 獲取 code */ public int getCode(){ return this.code; } /** * 獲取 value */ public String getValue(){ return this.value; } /** * 獲取變數名列表 */ public static MyEnums[] getVariables(){ return values(); } /** * 根據code獲取value */ public static String getValue(int code){ for(MyEnums myEnums:values()){ if(code==myEnums.code){ return myEnums.value; } } return ""; } }
結果: