Sunday, November 22, 2009

Array of Generic Type

I was asked why one cannot create an array of generic type, which means this line cannot compile:


// the below doesn't compile
ArrayList<Integer>[] arrayOfLists = new ArrayList<Integer>[7];


The compiler doesn't like the creation part, on the right, while the declaration alone, on the left, goes fine. This issue is widly discussed, e.g. nicely described here.

There are many ideas why it is forbidden and many suggestions for workarounds. But the nice colleague who asked me this question liked the most the workaround I suggested him, which is very simple.

I started by asking why he needs this.

And he explained that he needs to manage some info for 7 days a week:


// the below doesn't compile
ArrayList<SomeInfo>[] weeklyInfo = new ArrayList<SomeInfo>[7];


I suggested to create two new classes, DailyInfo and WeeklyInfo:


class DailyInfo {
    private ArrayList<SomeInfo> dailyInfo = new ArrayList<SomeInfo>();
    ...
}

class WeeklyInfo {
    private DailyInfo[] dailyInfo = new DailyInfo[7];
    ...
}


In most cases this would be the right object oriented approach, which by the way solves the problem of array of generic type.