I have the following two methods intended to filter out elements within a Collection that are instances of a some Class. This first method compiles OK, whereas the second does not.
The only change from the first to the second method is in the generic type definiton of the output Collection.
I'd like to know why the second method does not compile, since as far as I know it seems to perform a safe operation. May a helper method be useful?, if yes how should it be coded?.
public static <T> Collection<T> firstFilterCollection(Collection<?> sourceCollection, Class<T> classToFilter) throws InstantiationException, IllegalAccessException {
Collection<T> destinationCollection = sourceCollection.getClass().newInstance();
for (Object object : sourceCollection) {
if (classToFilter.isInstance(object)) {
T t = classToFilter.cast(object);
boolean add = destinationCollection.add(t);
}
}
return destinationCollection;
}
public static <T> Collection<? extends T> secondFilterCollection(Collection<?> sourceCollection, Class<T> classToFilter) throws InstantiationException, IllegalAccessException {
Collection<? extends T> destinationCollection = sourceCollection.getClass().newInstance();
for (Object object : sourceCollection) {
if (classToFilter.isInstance(object)) {
T t = classToFilter.cast(object);
boolean add = destinationCollection.add(t);
}
}
return destinationCollection;
}