希望有一個簡單的問題。我正在考慮實現一個擁有多個集合和HashMaps的類的最佳方式,其中類需要知道它們何時被修改以外的類 - 即添加/刪除/更改的項目。每個集合/散列映射現在都需要在我的課堂中作爲公共獲取者公開。
所以我的基本類看起來如下...
public class MyClass {
protected final HashMap<String, String> _values = new HashMap<String, String>();
protected final ArrayList<MyOtherClass> _other = new ArrayList<MyOtherClass>();
protected final ArrayList<MyOtherClass2> _other2 = new ArrayList<MyOtherClass2>();
// ... implementation
public HashMap<String, String> getValues() {
return _values;
}
public ArrayList<MyOtherClass> getMyOtherClassList() {
return _other;
}
public ArrayList<MyOtherClass2> getMyOtherClassList2() {
return _other2;
}
public String getContent() {
// build the content based on other/other2...
StringBuilder sb = new StringBuilder();
// iterate through both collections to build content...
// ...
return sb.toString();
}
}
public getMyOtherClass {
public String name; // has getter and setter
public String value; // has getter and setter
}
public getMyOtherClass2 {
public String name; // has getter and setter
public String value; // has getter and setter
public String somethingElse; // has getter and setter
}
我想基於內容的長度,即 -
_values.add("Length", getContent().length);
所以添加一個鍵/值對_values根據添加到_other和_other2的內容,長度值是動態的。
這個問題暴露了_values和_other與公共getter是類外的任何東西都可以修改它們。課程將不知道項目是否已被修改。
我能想到的一些解決方案是使collection/hashmap只讀 - 但是這會引發一個運行時異常 - 如果是這種情況,我希望編譯器指出它們是隻讀的並且拋出一個例外,但我不知道這是否可能。
另一種方法是爲每個集合/地圖添加一個add/remove並相應地更新Length屬性 - 但是,如果MyOtherClass中的值發生更改,MyClass仍然不知道它。
或者編寫我自己的Hashmap/List/Collection來確定何時添加/刪除項目,並且可能在getMyOtherClass,getMyOtherClass2上具有屬性更改偵聽器。
任何漂亮的解決方案呢?
感謝,
Andez
丹,好點。我手動複製和粘貼我的示例類,所以appologies。但是List <>也是一個接口;-) – Andez 2012-08-17 12:39:15