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