Hello!
This code is simplified as much as I can from a more complex class structure. In the real code, there were sub-types of the Integer and Double types I use here.
I'm trying to use Java Generics with a type parameter. If the user requests the type of Number.class
, we want to combine the List<Integer>
list and the List<Double>
list into a single list.
While the code works, I cannot get ride of the unchecked cast warning (see the TODO tag). The warning is :
Type safety: Unchecked cast from
List<Integer>
toCollection<? extends T>
But, if I remove the cast, I get a compile error :
The method
addAll(Collection<? extends T>
) in the typeList<T>
is not applicable for the arguments (List<Integer>
).
Suggestions welcome, and thanks!
Bill
package com.foo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public class Generics1 {
static final List<Integer> intList = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4));
static final List<Double> dblList = new ArrayList<Double>(Arrays.asList(1.1, 2.2, 3.3));
public static <T extends Number> List<T> getObjects(Class<T> type) {
List<T> outList = new ArrayList<T>();
if (type == Number.class) {
// user asked for everything
// TODO: unchecked cast warnings here should be fixed
outList.addAll((Collection<? extends T>) intList);
outList.addAll((Collection<? extends T>) dblList);
} else {
//
// user asked for subtype of number
//
if (Integer.class.isAssignableFrom(type)) {
for (Integer i : intList) {
if (type.isInstance(i)) {
T obj = type.cast(i);
outList.add(obj);
}
}
}
if (Double.class.isAssignableFrom(type)) {
for (Double d : dblList) {
if (type.isInstance(d)) {
T obj = type.cast(d);
outList.add(obj);
}
}
}
}
return outList;
}
public static void main(String[] args) {
System.out.println ("HI!");
System.out.println ("integers: " + getObjects(Integer.class));
System.out.println ("doubles: " + getObjects(Double.class));
System.out.println ("numbers: " + getObjects(Number.class));
}
}