【问题标题】:how to access Dictionary data within an Arraylist in Java?如何在 Java 中访问 Arraylist 中的字典数据?
【发布时间】:2012-03-07 19:10:06
【问题描述】:

我正在创建 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?

提前非常感谢:)

【问题讨论】:

  • 我不确定我是否得到了这个问题;您将获得适当的列表条目并像往常一样访问字典。或者遍历列表,检查每个字典的键。
  • 我不确定您要做什么,但来自字典 javadocs:NOTE: This class is obsolete. New implementations should implement the Map interface, rather than extending this class.。我认为也许您应该改用 HashMaps,如果您想使用相同的键检索多个值,您可能可以使用带有 putAll 方法的新 HashMap ...只是猜测
  • 对不起,我知道这听起来像是一个真正的初学者类型的问题。我正在开发一个棋盘类型的游戏,我们在层之上有层。每一层都是一个字典,而板子本身就是数组列表。没有直接的方法可以立即从我知道的数组列表中访问数据。我希望这能回答一些问题。
  • 感谢 jambriz,然后研究 HashMaps。

标签: java dictionary arraylist


【解决方案1】:

正如您在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>();

并确保使用正确的泛型类型(第二个必须是您的dataVars 拥有的类型)

【讨论】:

  • 谢谢,您的回答既给了我需要的答案,也给了我更好的选择路线。
【解决方案2】:

也许是这样的:

al.get(0).get("key1");

【讨论】:

    【解决方案3】:

    由于testDict 位于位置0(ArrayList 的第一个元素),您可以使用get(0). 检索它。

    例子:

    Dictionary firstDict = (Dictionary) al.get(0);
    Object key1Data = firstDict.get("key1");  
    

    Ps:如果允许使用泛型,它可以极大地改进您的代码。

    还有一点是……为什么是Dictionary 而不是Map

    【讨论】:

    • 我已经有一段时间没有真正用 java 编码了。感谢像您这样出色的成员,我了解到这不是理想的方法。地图是
    【解决方案4】:

    不知道你为什么要这样保留你的字典,但你可以简单地循环你的字典。

    public Data getData(String key) {
        for(Dictionary dict : al) {
            Data result = dict.get(key);
            if(result != null)
                return result;
            }
        return null;
    }
    

    【讨论】:

      猜你喜欢
      • 2013-09-04
      • 2021-09-20
      • 2013-10-06
      • 2019-11-25
      • 2017-10-25
      • 2022-01-16
      • 2019-08-20
      • 2020-02-28
      • 1970-01-01
      相关资源
      最近更新 更多