I’m trying to use the code below to create a multidimensional ArrayList. My code populates the inner ArrayList (localSolutions) just fine, but when I try an add that ArrayList to the outer ArrayList (solutions), something goes wrong, and it adds empty ArrayLists 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;
}
On a final note: would it be better to use a HashMap of ArrayLists (eventually I’m going to be creating CDF’s for max values up to about 10k)?
You are clearing the localSolutions list.
In Java you copy by value only the reference to an Object not the actual object itself. So when you add the localSolutions list in your solutions list, both the localSolutions reference and the first entry of the solutions list, point to the same object.
Thus, when you clear the localSolutions list, you effectively clear the first entry on your solutions list.