[英]how to access Dictionary data within an Arraylist in Java?
我正在創建Dictionary和諸如此類的ArrayList。
Dictionary testDict, testDict2 = null;
ArrayList al = new ArrayList();
testDict.put ("key1", dataVar1);
testDict.put ("key2", dataVar2);
testDict2.put ("key1", dataVar1);
testDict2.put ("key2", dataVar2);
al.add(testDict);
al.add(testDict2);
現在我的問題是,如何訪問字典中的數據? 例如,例如,如何使用al從testDict檢索key1?
提前謝謝了 :)
也許這樣:
al.get(0).get("key1");
由於testDict
位於位置0( ArrayList
第一個元素),因此可以使用get(0).
檢索它get(0).
。
例:
Dictionary firstDict = (Dictionary) al.get(0);
Object key1Data = firstDict.get("key1");
附言:如果允許您使用泛型,那么泛型可以極大地改善您的代碼。
另一點是...為什么選擇Dictionary
而不選擇Map ?
正如您可以在Java Docs中閱讀的那樣,所有Dictionary對象(請注意,例如Hashtable就是其中之一)都有一個Object get(Object key)
來訪問其元素。 在您的示例中,您可以像這樣訪問textDict
中的key1
項的值:
// first access testDict at index 0 in the ArrayList al
// and then it's element with key "key1"
al.get(0).get("key1");
請注意,您無處可初始化Dictionary對象,而Dictionary
類是抽象的。 因此,例如,您可以出於以下目的使用Hashtable
(或者,如果不需要同步訪問,請使用更快的HashMap
):
testDict = new Hashtable<String, String>();
並確保使用正確的泛型類型(第二種必須是dataVar
的類型)
不知道為什么要保留這樣的字典,但是您可以簡單地遍歷字典。
public Data getData(String key) {
for(Dictionary dict : al) {
Data result = dict.get(key);
if(result != null)
return result;
}
return null;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.