gpt4 book ai didi

java - 如何访问 Java 中 Arraylist 中的字典数据?

转载 作者:行者123 更新时间:2023-11-29 07:16:01 25 4
gpt4 key购买 nike

我正在创建像这样的 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?

提前致谢:)

最佳答案

正如您在 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 所具有的类型)

关于java - 如何访问 Java 中 Arraylist 中的字典数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9607562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com