2

I have a array of ArrayList as defined below.

List<ArrayList<String>> reverseRange = new ArrayList<ArrayList<String>>();

and I set it to:

[[a, b, c, d, e, f, g, h, i], [a, b, c, d, e, f, g, h, i], [a, b, c, d, e, f, g, h, i], [a, b, c, d, e, f, g, h, i], [a, b, c, d, e, f, g, h, i], [a, b, c, d, e, f, g, h, i], [a, b, c, d, e, f, g, h, i], [a, b, c, d, e, f, g, h, i]]

by:

for (int i = 0; i < naive.size(); i++) { reverseRange.add(A); }

where A = [b, c, d, e, f, g, h, i]

I want to delete an object from specific list. Like:

reverseRange.get(0).remove("a");

but when I do that, it removes "a" from all lists and the result becomes:

[[b, c, d, e, f, g, h, i], [b, c, d, e, f, g, h, i], [b, c, d, e, f, g, h, i], [b, c, d, e, f, g, h, i], [b, c, d, e, f, g, h, i], [b, c, d, e, f, g, h, i], [b, c, d, e, f, g, h, i], [b, c, d, e, f, g, h, i]]

What I am doing wrong?

Javanshir
  • 772
  • 2
  • 7
  • 20
  • 4
    How did you fill this *array*? It looks like it contains same list instance multiple times, instead of having multiple list instances with same characters. – Pshemo Sep 13 '15 at 15:08
  • for (int i = 0; i < naive.size(); i++) { reverseRange.add(A); } where A = [b, c, d, e, f, g, h, i] – Javanshir Sep 13 '15 at 15:11
  • 1
    That confirms it. You are adding *same* instance of list from `A` reference to `reverseRange` list multiple times. Try with `for (int i = 0; i < naive.size(); i++) { reverseRange.add(new ArrayList<>(A)); }` which in each iteration will create separate instance of `ArrayList`, fill it with elements from `A`, and then place it in `reverseRange`. – Pshemo Sep 13 '15 at 15:12
  • 1
    Yes, that was the problem. Thank you. Seems like I was only referencing to A multiple times – Javanshir Sep 13 '15 at 15:16
  • @SotiriosDelimanolis Maybe the questions have strong connection to eachother, they are asking essentially different things. Closing this question was a bad thing. – peterh Sep 13 '15 at 16:07

0 Answers0