Re: Question about returning generics
aaronfude@gmail.com wrote:
Suppose I have an array of diverse types and I want extract all
objects of a certain type (e.g. Date) and return it as a vector of
that type. Is it possible to write a function that will return arrays
of different types depending on the input parameters. I guess I have
just about answered my own question negatively, but I'm hoping for
something like this:
Vector<Date> dates = collect(set, Date.class);
Vector<Double> doubles = collect(set, Double.class);
Arrays or Vectors.
Not possible, right?
I don't see why it should be impossible.
public static <T> List<T> collect(
Iterable<?> items, Class<? extends T> target
) {
if (target.isPrimitive()) {
throw new IllegalArgumentException();
}
List<T> found = new java.util.ArrayList<T>();
for (Object item : items) {
if (target.isInstance(item)) {
found.add(item);
}
}
return found;
}
@SuppressWarnings("unchecked")
public static <T> T[] collect(
Iterable<?> items, Class<T> target
) {
List<T> found = collect(items, target);
return found.toArray((T[])
java.lang.reflect.Arrays.newInstance(target, found.size())
);
}
[Disclaimer: Not tested, or even compiled.]
I am not, however, convinced that this is a brilliant design.
Tom Hawtin