I am creating Dictionary and an ArrayList such as this.
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);
now my issue here is, how can I access the data within the dictionaries? Like for example how would I retrieve key1 from testDict using al?
Many thanks in advance :)
也许这样:
al.get(0).get("key1");
Since testDict
is at position 0 (first element of your ArrayList
) you can retrieve it with get(0).
.
Example:
Dictionary firstDict = (Dictionary) al.get(0);
Object key1Data = firstDict.get("key1");
Ps: Generics can greatly improve your code if you are allowed to use it.
Another point is... Why Dictionary
and not Map ?
As you can read in the Java Docs all Dictionary objects (note that eg Hashtable is one of them) have a method Object get(Object key)
to access it's elements. In your example you could access the value of the entry key1
in textDict
like that:
// first access testDict at index 0 in the ArrayList al
// and then it's element with key "key1"
al.get(0).get("key1");
Note, that you nowhere initialize your Dictionary objects and that the Dictionary
class is abstract. So you could for example use a Hashtable
(or if you don't need synchronized access use a faster HashMap
instead) for your purpose like this:
testDict = new Hashtable<String, String>();
And make sure to use the correct generic types (the second one has to be the type that your dataVar
s have)
Not sure why'd you want keep your dictionaries like that, but you can simply loop over your dictionaries.
public Data getData(String key) {
for(Dictionary dict : al) {
Data result = dict.get(key);
if(result != null)
return result;
}
return null;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.