简体   繁体   中英

How to access String within an ArrayList within an ArrayList within a HashMap?

So I have this ArrayList full of Strings

ArrayList<String> colours = new ArrayList<>();
    colours.add("Red");
    colours.add("Blue");

And that ArrayList is stored in another ArrayList

ArrayList<ArrayList> container = new ArrayList<>();
    container.add(colors);

And that ArrayList is stored in a HashMap

HashMap<Integer, ArrayList> map = new HashMap<>();
    map.put(1, container);

How do I access "red"? I tried

System.out.println(map.get(1).get(0).get(0));

But it gave a

Error: java: cannot find symbol
  symbol:   method get(int)
  location: class java.lang.Object

You should not use raw types like ArrayList<ArrayList> but use fully "cooked" types such as ArrayList<ArrayList<String>> (or even better, List<List<String>> ).

Likewise, instead of HashMap<Integer, ArrayList> , use HashMap<Integer, ArrayList<ArrayList<String>>> (or even better, Map<Integer, List<List<String>>> ).

If you make these changes, your map.get(1).get(0).get(0) expression will compile correctly.

Try to replace this:

  HashMap<Integer, ArrayList> map = new HashMap<>();

With:

  HashMap<Integer, List<ArrayList<String>>> map = new HashMap<Integer, List<List<String>>>();

In this case you can do this:

  System.out.println(map.get(1).get(0).get(0));

because the 1st get(1) for the map , the 2nd get(0) for the 1st List and the 3th get(0) for the 2nd List .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM