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];
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);
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>>();
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>();
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With