Take values from ArrayList> [closed]

2019-09-30 03:23发布

问题:

I have a problem about getting a value from my ArrayList<HashMap<String, String>>.

My code is:

ArrayList<HashMap<String, String>> myArrayList;

and then:

HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
myArrayList.add(map);

If I want to get the name, for example, I tried as follow but I obtain a runtime error (the application crashes):

System.out.println(myArrayList.get(1).get(TAG_NAME));

How can I solve it?

Thank you very much!

回答1:

System.out.println(myArrayList.get(1).get(TAG_NAME));

ArrayList is 0-based. get(0) instead.



回答2:

You can loop through the list like this

   for(Map<String, String> map : myArrayList)
    {
        String tagName = map.get(TAG_NAME);
        System.out.println(tagNAme);
    }