I am trying to create an ArrayList from ArrayLists. I want to create 25 ArrayLists and have those ArrayList that have different values. The goal is to create a sorted dictionary by word length.
My code looks like
for(int i = 0; i < 25; i++) list2D.add(list); for(int i = 0; i < stringList; i++) list2D.get(stringList.get(i).length()).add(stringList.get(i))
The problem is that each list contains the same values ββafter completion.
I know why the problem is happening. "list" is an ArrayList, ArrayList is an object, and if you are editing an object, then everything containing this object will be edited.
To fix the problem, I tried
for(int i = 0; i < 25; i++){ list = new ArrayList<String>(); for(int i2 = 0; i2 < stringList.size(); i2++){ if(stringList.get(i).length() == i) list.add(stringList.get(i2)); } list2D.add(list); }
But when I test my "list2D"
for(int i = 0; i < 25; i++) System.out.print(list2D.get(i).size()+" ");
I get
0 0 0 0 0 58 110 0 58 110 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
and I have no idea why ...
It may also be appropriate to note that stringList contains 58110 values.
Also I do not want to create 25 different ArrayLists!
java object arraylist
java
source share