Aleksandr Dubinsky
Aleksandr Dubinsky

Reputation: 23515

Casting a generic List to a subtype (unsafe contravariance)

Assuming I have a List<Base> that I know contains only elements of type Derived, how can I force a cast to a List<Derived>?

Upvotes: 0

Views: 77

Answers (2)

Aleksandr Dubinsky
Aleksandr Dubinsky

Reputation: 23515

My solution:

  public static <T> List<T>
cast(List<? super T> list, Class<T> clazz) {

        if( list.stream().allMatch( clazz::isInstance ) )
            return (List<T>) list;
        else
            throw new IllegalArgumentException ("Not all inputs are of class " + clazz.getName());
    }

Upvotes: 1

Chris K
Chris K

Reputation: 11927

public static void main(String[] args) {
    List<Number> foo = new ArrayList<>();

    List<Integer> a = cast(foo);

    System.out.println("a = " + a);
}

public static <T, C extends T> List<C> cast( List<T> l ) {
    return (List<C>) l;
}

Upvotes: 0

Related Questions