Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly create an ArrayList of ArrayLists?

I am trying to create an ArrayList of ArrayLists. I want to create 25 ArrayLists and have those ArrayList hold different values. The goal being 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 every list contains the same values after it finishes.

I know why the problem is happening. "list" is an ArrayList, ArrayList's are objects and if you edit an object then everything containing that 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 58110 0 58110 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

and I have no idea why...

Also it might be relevant to note that stringList contains 58110 values.

Also I don't want to have to make 25 different ArrayLists!

like image 466
java Avatar asked Nov 03 '13 21:11

java


2 Answers

I would try the following to do a single pass of the stringList

List<List<String>> dict = new ArrayList<>();
for(string s: stringsList) {
    int len = s.length();
    // add new array lists as required, could be any length, assuming << 100
    while(dict.size() <= len) dict.add(new ArrayList<String>());
    // add the string to the right list.
    dict.get(len).add(s);
}
like image 172
Peter Lawrey Avatar answered Sep 22 '22 06:09

Peter Lawrey


This is easy. For example, you can create them like this: http://ideone.com/3NZwWU

// just for convenience, initializes arraylist with values
static <T> ArrayList<T> AL(T... values) {
    ArrayList<T> r = new ArrayList<T>();
    for (T x : values) {
        r.add(x);
    }
    return r;
}

public static void main (String[] args) throws java.lang.Exception
{
    System.out.println(AL(
        AL(3,2,24,131),
        AL("this", "is", "second", "array")));
    // prints `[[3, 2, 24, 131], [this, is, second, array]]`

}
like image 41
Display Name Avatar answered Sep 18 '22 06:09

Display Name