有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在Java中访问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

非常感谢:)


共 (1) 个答案

  1. # 1 楼答案

    正如您在Java Docs中所读到的,所有字典对象(注意,例如Hashtable就是其中之一)都有一个方法Object get(Object key)来访问它的元素。在您的示例中,您可以访问textDictkey1项的值,如下所示:

    // first access testDict at index 0 in the ArrayList al 
    // and then it's element with key "key1"
    al.get(0).get("key1");
    

    请注意,您不需要初始化字典对象,而且Dictionary类是抽象的。例如,您可以使用Hashtable(或者如果不需要同步访问,可以使用更快的HashMap)来实现以下目的:

    testDict = new Hashtable<String, String>();
    

    并确保使用正确的泛型类型(第二个必须是dataVar的类型)