Reputation: 8020
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)?
Upvotes: 4
Views: 1500
Reputation: 39950
You're doing:
localSolutions.clear();
Adding a list to another list doesn't add a copy of the list, it adds the same list object. What your code is doing in the outerloop is filling the same list with elements, emptying it, and adding it to solutions
. solutions
contains max
references to the same, empty list.
What you want to do is:
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);
}
Upvotes: 3
Reputation: 11592
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.
Upvotes: 3