2013-03-06 87 views
-1

存儲性能我有類似下面的類:Java的:在一個對象

public class Prefs { 
    public static final int PREF_NAME = 0; 
    public static final int PREF_SURNAME = 1; 
    public static final int PREF_LOCATION = 2; 

    String[] defaults = { "unknown", "unknown", "nowhere" } 
    String[] prefs; 

    public String getPref(int id) { 
     return prefs[id]; 
    } 
} 

所以我可以使用下面的語法:

Prefs p = new Prefs(); 
p.setDefaults() // irrelevant code not included 
p.getPref(Prefs.PREF_LOCATION); // much more readable than getPref(2); 

是這種做法是否正確?有沒有更好的選擇來做到這一點?

編輯:請提供一個簡單的例子。

回答

1

我認爲enum將正是你需要和完美。

+0

我也有'setPref(id,val)'方法,所以我認爲我不能使用枚舉。我從來沒有用過它們,但我認爲它只是常量。 – Twinone 2013-03-06 08:54:26

+0

確定在這種情況下最好使用'java.util.Properties' – 2013-03-06 08:56:13

0

如果您在「首選項」的元素將是動態列表,你可能要考慮使用一個哈希表: -

http://docs.oracle.com/javase/6/docs/api/java/util/Hashtable.html

這將讓你有一個要提到的一個關鍵具體元素。

(來自javadoc)本示例創建一個數字散列表。它採用了數字的名字作爲鍵:

Hashtable numbers = new Hashtable(); 
numbers.put("one", new Integer(1)); 
numbers.put("two", new Integer(2)); 
numbers.put("three", new Integer(3)); 

提取號碼,使用下面的代碼:

Integer n = (Integer)numbers.get("two"); 
if (n != null) { 
    System.out.println("two = " + n); 
} 

另外,如果你想隨機訪問,你可以使用ArrayList。

http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html

0

要麼使用enumValuedEnum(org.appache.commons),當值不會改變。
在ValuedEnum中,您可以提供自定義文本,對於一個值,標準枚舉使用枚舉字段名稱作爲文本。

如果您使用的是java枚舉,請考慮使用您爲enum明確賦值的方法(通過爲參數「value」提供枚舉constrcutor)。

javarevisited

public enum Currency { 
     PENNY(1), NICKLE(5), DIME(10), QUARTER(25); 
     private int value; 

     private Currency(int value) { 
       this.value = value; 
     } 

}; 

這Valied枚舉的方法,當你想確保值不會改變(例如用於persitence)是neccessary。 java ordinal()不能提供。