Oleg Vazhnev
Oleg Vazhnev

Reputation: 24067

casting from List<B extends A> to List<A> using intermediate wildcard - safe?

I've noticed following java behavior, which confuse me a little:

import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(String[] args) {
        new Test().test();
    }

    public void test() {
        List<B> b = new ArrayList<>();
        b.add(new B());

        // doesn't compile
        // List<A> a = (List<A>) b;
        List<A> a = (List<A>) (List<? extends A>) b;

        System.out.println(a.get(0));
    }

    private static class A {
        @Override
        public String toString() {
            return "A{}";
        }
    }

    private static class B extends A{
        @Override
        public String toString() {
            return "B{}";
        }
    }

}

And it prints B{}.

If I have List<B extends A> and I want to call a method which expects List<A> is it safe or not to do a cast like in the example above?

Why java prohibits (List<A>), but allows (List<A>) (List<? extends A>)?

Answer to similar question Java: Casting from List<B> to List<A> when B implements A? says that "You cannot cast it like that."

My question is - why I was able to cast and what is the consequence of such cast.

Upvotes: 2

Views: 55

Answers (0)

Related Questions