Create an ArrayList from ArrayList <Integer>
I am trying to use the code below to create a multidimensional ArrayList array. My code fills the internal ArrayList (localSolutions) array very well, but when I try to add an ArrayList to the external ArrayList (s), something goes wrong and empty ArrayLists are added instead.
public class MathCapstone { public static void main(String[] args) { ArrayList<ArrayList<Integer>> list = entireList(10); for(int q = 0;q<list.size();q++) { System.out.println(list.get(q)); } public static ArrayList<ArrayList<Integer>> entireList(int max) { ArrayList<ArrayList<Integer>> solutions = new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> localSolutions = new ArrayList<Integer>(); for(int i = 1; i <= max; i++) { for(int j = 1; j < i; j++) { //System.out.println(j + "mod" + i + "=" + (j*j)%i); if ((j*j)%i == 1) { localSolutions.add(j); } } //System.out.println(localSolutions.toString()); solutions.add(localSolutions); localSolutions.clear(); } return solutions; } In a final note: would it be better to use a HashMap from ArrayLists (in the end I'm going to create CDFs for max values ββup to 10k)?
You clear the localSolutions list.
In Java, you copy by value only the reference to the object, not the object itself. Therefore, when you add the localSolutions list to the list of solutions , both the localSolutions link and the first decision record>, specify the same object.
Thus, when you clear the localSolutions list, you effectively clear the first entry in the solution list.
You doing:
localSolutions.clear(); Adding a list to another list does not add a copy of the list; it adds the same list object. What your code does in the outer closure fills the same list with elements, omitting it and adding it to solutions . solutions contains max links to the same empty list.
What do you want to do:
ArrayList<ArrayList<Integer>> solutions = new ArrayList<ArrayList<Integer>>(); for(int i = 1; i <= max; i++) { ArrayList<Integer> localSolutions = new ArrayList<Integer>(); for(int j = 1; j < i; j++) { //System.out.println(j + "mod" + i + "=" + (j*j)%i); if ((j*j)%i == 1) { localSolutions.add(j); } } //System.out.println(localSolutions.toString()); solutions.add(localSolutions); }