Reputation: 83
I've following question: Is it possible to do something like that:
class Sample {
public static void main(String[] args) {
List<Fruit> fruits = new ArrayList<>();
fruits.add(apple);
fruits.add(orange);
List<Apple> apples = new ArrayList<>();
copyToSubType(fruits, apples, Apple.class);
}
private <T> void copyToSubType(List<T> source, List<? extends T> target, Class cls) {
for (T element : source) {
if (element.getClass() == cls) {
target.add(element);
}
}
}
}
I'm trying to find some kind of general method that allows me to copy elements from concrete type to the list that contains only such types. I was thinking if it is possible to use the wildcards... but it seems that my approach isn't correct.
Upvotes: 0
Views: 53
Reputation: 1357
You can use :
if (element.getClass().isAssignableFrom(cls) {
target.add((S) element);
}
Upvotes: 0
Reputation: 79875
Yes, you can do that. But your method will vary with both the type of the source list, and the subtype that you want to detect. So you'll need it to have type parameters for them both.
Something like this:
private <T,S extends T> void copyToSubType(List<T> source, List<S> target, Class<S> cls) {
for (T element : source) {
if (cls.isInstance(element)) {
target.add((S) element);
}
}
}
Upvotes: 2