简体   繁体   English

如何在Java中访问Arraylist中的Dictionary数据?

[英]how to access Dictionary data within an Arraylist in Java?

I am creating Dictionary and an ArrayList such as this. 我正在创建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);

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? 例如,例如,如何使用al从testDict检索key1?

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). 由于testDict位于位置0( ArrayList第一个元素),因此可以使用get(0).检索它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 ? 另一点是...为什么选择Dictionary而不选择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. 正如您可以在Java Docs中阅读的那样,所有Dictionary对象(请注意,例如Hashtable就是其中之一)都有一个Object get(Object key)来访问其元素。 In your example you could access the value of the entry key1 in textDict like that: 在您的示例中,您可以像这样访问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");

Note, that you nowhere initialize your Dictionary objects and that the Dictionary class is abstract. 请注意,您无处可初始化Dictionary对象,而Dictionary类是抽象的。 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: 因此,例如,您可以出于以下目的使用Hashtable (或者,如果不需要同步访问,请使用更快的HashMap ):

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) 并确保使用正确的泛型类型(第二种必须是dataVar的类型)

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM