user1845029
user1845029

Reputation: 1125

ArrayList of Arraylist a remove function affects all Arraylists

I created an ArrayList of 80 Arraylists. Each ArrayList inside, has the values 1-9.

However, when I delete a value from one of the Arraylists its deleted in all of them.

ArrayList<List> available = new ArrayList<List>();
ArrayList<Integer> possibleValues = new ArrayList<Integer>();



    for(int j = 1; j<=9; j++){
        possibleValues.add(j);
    }

    for (int i = 0; i<=80; i++){
        available.add(possibleValues);  
    }

     int b = (int) available.get(0).get(2);
     available.get(0).remove(0);
     String s = available.get(80).toString();
     System.out.println(" " + s);

}

Any help is appreciated.

Upvotes: 1

Views: 148

Answers (4)

Poornima
Poornima

Reputation: 928

You are adding the same ArrayList 81 times. ArrayList is a reference type, so any change to it will affect all items. It should be:

available.add(new ArrayList(possibleValues));

Upvotes: 0

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26094

Because you are adding the values to same ArrayList. You need to create new Arraylist for 0 to 80 iterations.

for(int j = 1; j<=9; j++){
        possibleValues.add(j);// one ArrayList with values.
}


for (int i = 0; i<=80; i++){
        available.add(possibleValues); //Here adding same Arraylist 80 times.  
}

Try this one

  ArrayList<List> available = new ArrayList<List>();
  ArrayList<Integer> possibleValues = new ArrayList<Integer>();

  for (int i = 0; i<=80; i++){
    possibleValues = new ArrayList<Integer>();
    for(int j = 1; j<=9; j++){           
        possibleValues.add(j);
    } 
    available.add(possibleValues);  
  }

Upvotes: 1

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44449

That's because you're adding the same ArrayList to every index of the outer ArrayList . Any change to this ArrayList will automatically result in a change in the other ArrayList .

Nest your loops to always create a new ArrayList or construct a new ArrayList from the already existing one.

Upvotes: 1

rgettman
rgettman

Reputation: 178303

The problem here is that you've added the same ArrayList possibleValues to available 81 times. So, the available list contains 81 references to the same possibleValues list.

Any changes made to the list are visible through any of those 81 references.

If you don't want the changes visible to all references, just one, then you need to make 81 copies of the list to add:

for (int i = 0; i<=80; i++){
    available.add(new ArrayList<Integer>(possibleValues));  
}

Upvotes: 6

Related Questions