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.
Probably not a good idea to design your API in terms of raw arrays, nor to use
Vector (essentially obsolete, and has been for many years). But using
java.util.List it seems to work OK:
-- chris
======== Utils.java ============
import java.util.*;
public class Utils
{
public static <X>
List<X>
collect(List<Object> list, Class<X> clobj, boolean allowNull)
{
List<X> filtered = new ArrayList<X>();
for (Object elem : list)
{
if (allowNull && elem == null)
filtered.add(null);
else if (clobj.isInstance(elem))
filtered.add(clobj.cast(elem));
}
return filtered;
}
}
======== Test.java ============
import java.util.*;
public class Test
{
public static void
main(String[] args)
{
List<Object> all = Arrays.asList(new Object[] {
"one",
null,
true,
false,
'c',
88.88,
100
});
System.out.println("Strings (or null):");
List<String> strings = Utils.collect(all, String.class, true);
for (String s : strings)
System.out.println("\t" + s);
System.out.println("Numbers:");
List<Number> numbers = Utils.collect(all, Number.class, false);
for (Number n : numbers)
System.out.println("\t" + n);
}
}
=============================