advena
advena

Reputation: 83

how to deal with type in java bounded wildcards

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

Answers (2)

Maas
Maas

Reputation: 1357

You can use :

if (element.getClass().isAssignableFrom(cls) {
    target.add((S) element);
}

Upvotes: 0

Dawood ibn Kareem
Dawood ibn Kareem

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

Related Questions