Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding to double Arraylist in HashMap

I am trying to add pairs that add up to a certain number in java and one of the ways I am trying to attempt this is to create a double ArrayList within my HashMap. If I add 1 and 2 to my list, I will get 3 as my key. For example:

    HashMap<Integer, ArrayList<ArrayList<Integer>>> map = new HashMap<>();
    ArrayList<Integer> list = new ArrayList<>();
    list.add(1);
    list.add(2);
    map.put(list.get(0) + list.get(1), new ArrayList<>(list));

but I keep getting a ‘method is not applicable in the type HashMap<Integer,ArrayList<ArrayList>> is not applicable for the arguments (int, new ArrayList<>(list))’

I’ve also tried

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    new ArrayList<>(new ArrayList<>(list))

thinking that I might need to initialize the bigger matrix first but I end up with the same error sadly.

>Solution :

This line:

new ArrayList<>(list)

creates a flat ArrayList<Integer>, while the HashMap is expecting ArrayList<ArrayList<Integer>>. By the same token, new ArrayList<>(new ArrayList<>(list)) also creates a flat Integer list because you are just doing the same thing twice. See the API document for ArrayList

This is one way that would work given the 2-D list setup:

HashMap<Integer, List<List<Integer>>> map = new HashMap<>();
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
List<List<Integer>> outer = new ArrayList<>();
outer.add(list);
map.put(list.get(0) + list.get(1), outer);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading