Reputation: 2499
I am trying to write the following code...
static ArrayList<RssItem>[][] list = new ArrayList<RssItem>[][];
This doesn't work. What am I doing wrong, if I am trying to create a list of ArrayList<RssItem>
?
Upvotes: 0
Views: 137
Reputation: 213213
You need to give the size on the RHS: -
static List<RssItem>[][] arr = (List<RssItem>[][])new List<?>[4][];
Size of column
is not needed, but you can give it too: -
static List<RssItem>[][] arr = (List<RssItem>[][])new List<?>[4][5];
NOTE: -
You cannot give a specific
type as a type parameter on the RHS
. You would have to use WildCard
. Specific type would only be given when you are instantiating your list
in the array.
To add something to your array, you can use this kind of loop: -
NOT Tested
List<RssItem>[][] arr = (List<RssItem>[][])new ArrayList<?>[4][4];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = new ArrayList<RssItem>();
arr[i][j].add(new RssItem());
}
}
for (List<RssItem>[] val: arr) {
for (List<RssItem> val2: val) {
System.out.println(val2);
}
}
P.S.: -
Please don't use 2-D array of List
. That is equivalent to a 3-D array. Even if you get the above loop to work somehow. It will make your code mess in future. And your life hell. There are many other data structures in Java, that you should consider, like a Map
, which is useful in such kind of situations.
Even, having a List
upto 3 levels is a very bad idea. So, please change your design.
Upvotes: 2
Reputation: 319
A generic array of Array lists = an array list of array lists
And that would be
ArrayList<ArrayList> list = new ArrayList<ArrayList>();
Upvotes: 0
Reputation: 19185
You cannot create an array of a generic type. So You will need to use cast.
List<RssItem>[][] arr = (List<RssItem>[][]) new ArrayList<?>[2][2];
But still it will be good to implement List of List ArrayList<ArrayList<Type>>
List<ArrayList<RssItem>> list = new ArrayList<ArrayList<RssItem>>();
arr[0][0] = new ArrayList<Integer>();
arr[0][0].add(10);
Upvotes: 2