Reputation: 5475
I'm trying to define an array for 3 ArrayLists, each containing a double array. I've used the following syntax:
ArrayList<double[]> testSamples[] = new ArrayList[] {
new ArrayList<double[]>(), new ArrayList<double[]>(), new ArrayList<double[]>()
};
However this generates a "warning: [unchecked] unchecked conversion" warning when I compile the code. Note: the code works fine, I'm just tried to fix my syntax (correctly) to resolve the warning. Since the code works, it appears to be supported by Java, I'm baffled as to why I can't write something like (which generates a compile error):
ArrayList<double[]> testSamples[] = new ArrayList<double[]>[] {
new ArrayList<double[]>(), new ArrayList<double[]>(), new ArrayList<double[]>()
};
What am I doing wrong?
Upvotes: 0
Views: 1004
Reputation: 122439
This is the usual problem with creating an array of a parameterized type. Why you cannot use new
to create an array of a parameterized type is a long topic that has been covered many times here; it basically has to do with how arrays perform runtime checks on the element types, but runtime checks cannot check type parameters.
Long story short, an unchecked warning of some kind is unavoidable (because it is indeed possible to make it violate the guarantees of the array type). If you don't mind the "unsafeness", the most kosher way to write it is to create the array using a wildcarded type instead of a raw type, and cast it to the proper type of array (yes, this is an unchecked cast):
ArrayList<double[]>[] testSamples =
(ArrayList<double[]>[]) new ArrayList<?>[] { ... }
Upvotes: 1
Reputation: 129507
You're implicitly converting from an array of the raw type ArrayList
to an array of ArrayList<double[]>
s. All in all, you shouldn't do something like this. If you know you will have 3 lists, then you can create a class to hold them instead:
class Container {
private ArrayList<double[]> list1;
private ArrayList<double[]> list2;
private ArrayList<double[]> list3;
... // constructors and whatnot
public ArrayList<double[]> getList(int i) { // analog of testSamples[i]
switch (i) {
case 0:
return list1;
case 1:
return list2;
case 2:
return list3;
default:
throw new IllegalArgumentException();
}
}
}
If the number of lists isn't fixed at 3, then you can use a List<ArrayList<double[]>>
instead.
Upvotes: 4