如何在Java中的Arraylist中访问Dictionary数据? [英] how to access Dictionary data within an Arraylist in Java?

查看:136
本文介绍了如何在Java中的Arraylist中访问Dictionary数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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文档所有Dictionary对象(注意,例如Hashtable是其中之一)具有方法 Object get(Object key)来访问它的元素。在您的示例中,您可以访问 textDict 中的条目 key1 的值:

  //首先在ArrayList al 
//中的索引0处访问testDict,然后是具有键key1
al的元素。得到(0)获得( 键1);

请注意,您无法初始化您的Dictionary对象,而 Dictionary class是抽象的。所以你可以使用 Hashtable (或者如果你不需要同步访问使用更快的 HashMap 代替)为此您的目的:

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

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


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 :)

解决方案

As you can read in the Java Docs all Dictionary objects (note that e.g. 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 dataVars have)

这篇关于如何在Java中的Arraylist中访问Dictionary数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆