Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize an Array of ArrayList [duplicate]

How can I initialize an Array of ArrayList<String>?

I tried this syntax but it didn't work:

ArrayList<String>[] subsection = new ArrayList<String>[4];
like image 553
user1343857 Avatar asked Apr 19 '12 11:04

user1343857


4 Answers

you can define like this :

ArrayList<String>[] lists = (ArrayList<String>[])new ArrayList[10];
    lists[0] = new ArrayList<String>();
    lists[0].add("Hello");
    lists[0].add("World");
    String str1 = lists[0].get(0);
    String str2 = lists[0].get(1);
    System.out.println(str1 + " " + str2);
like image 175
UVM Avatar answered Nov 12 '22 12:11

UVM


That syntax works fine for the non-generic ArrayList. (ideone)

But it won't work for the generic ArrayList<E>: (ideone)

This code:

ArrayList<String>[] subsection = new ArrayList<String>[4];

Gives a compiler error:

Main.java:8: generic array creation
        ArrayList<String>[] subsection = new ArrayList<String>[4];

For the generic version use an ArrayList<ArrayList<E>>:

ArrayList<ArrayList<String>> subsection = new ArrayList<ArrayList<String>>();
like image 45
Mark Byers Avatar answered Nov 12 '22 12:11

Mark Byers


Okay after comment, I thought well... your right why not.

Figured it out.

ArrayList[] test = new ArrayList[4];

test[3] = new ArrayList<String>();
test[3].add("HI");

System.out.println(test[3].get(0));

Though I will be honest, I am not really sure WHY this works.

Once you assign the first item of test as a new Collection, it will only allow all other items in the array to be that type. So you couldn't do

test[3] = new ArrayList<String>();
test[2] = new HashSet<String>();
like image 6
Dan Ciborowski - MSFT Avatar answered Nov 12 '22 11:11

Dan Ciborowski - MSFT


Look into generics as type clarification process, you can assign typed value to a variable of raw type AND vice versa. In core generics are a shortcut for the programmers to avoid making type casting too much, which also helps to catch some logical errors at compile time. At the very basics ArrayList will always implicitly have items of type Object.

So

test[i] = new ArrayList<String>(); because test[i] has type of ArrayList.

The bit

test[3] = new ArrayList<String>();
test[2] = new HashSet<String>();

did not work - as was expected, because HashSet simply is not a subclass of ArrayList. Generics has nothing to do here. Strip away the generics and you'll see the obvious reason.

However,

test[2] = new ArrayList<String>();
test[3] = new ArrayList<HashSet>(); 

will work nicely, because both items are ArrayLists.

Hope this made sense...

like image 2
Nar Gar Avatar answered Nov 12 '22 13:11

Nar Gar