6
ArrayList<HashMap<String, Integer>> myList = new ArrayList<HashMap<String, Integer>>();

    HashMap<String, Integer> check = new HashMap<String, Integer>();

我的数组列表中有一些哈希图,我想比较哈希图的重复项,例如 0,1 0,2 0,3 0,4....1,2 1,3 1,4.... .2,3 2,4 等

我正在做一个嵌套的 for 循环,但被困在如何访问哈希图并尝试了这个

for (int a =0; a<myList.size();a++){
            for(int b=a+1; b<myList.size();b++){
                for (String key : myList[a].check.keySet())
            }
        }

但这不起作用。如果它们在数组列表中,我如何访问我的哈希图的所有键?我怎样才能做到这一点?

4

2 回答 2

10

这是一个迭代的例子。我创建了虚拟数据来测试代码

private void ArrayListAndHashMap()
    {
        ArrayList<HashMap<String, Integer>> myList = new ArrayList<HashMap<String, Integer>>();


        HashMap<String, Integer> data1 = new HashMap<String, Integer>();
         data1.put("0",new Integer(1));
         data1.put("1",new Integer(2));
         data1.put("2",new Integer(3));
         data1.put("3",new Integer(4));

        HashMap<String, Integer> data2 = new HashMap<String, Integer>();
        data1.put("10",new Integer(10));
         data1.put("11",new Integer(20));
         data1.put("12",new Integer(30));
         data1.put("13",new Integer(40));

         myList.add(data1);
         myList.add(data2);


        for (int a =0; a<myList.size();a++)
        {
            HashMap<String, Integer> tmpData = (HashMap<String, Integer>) myList.get(a);
            Set<String> key = tmpData.keySet();
            Iterator it = key.iterator();
            while (it.hasNext()) {
                String hmKey = (String)it.next();
                Integer hmData = (Integer) tmpData.get(hmKey);

                System.out.println("Key: "+hmKey +" & Data: "+hmData);
                it.remove(); // avoids a ConcurrentModificationException
            }

        }       
    }

输出是

Key: 3 & Data: 4
Key: 2 & Data: 3
Key: 10 & Data: 10
Key: 1 & Data: 2
Key: 0 & Data: 1
Key: 13 & Data: 40
Key: 11 & Data: 20
Key: 12 & Data: 30
于 2013-04-12T20:21:35.997 回答
8

运算符[]只能用于数组。List 有一个get(int index)方法来获取给定索引处的元素:

for (String key : myList.get(a).keySet()) {
    ...
}

记录了 Java 类: http: //docs.oracle.com/javase/6/docs/api/

于 2013-04-12T19:58:29.367 回答