What will happen if you attempt to compile and run this code?

import java.util.*;

class A {}
class B extends A {}
class B1 extends A {}
class B2 extends A {}
class C1 extends B {}
class C2 extends B {}

public class AsListInt {
    public static void main(String[] args) {
1.        List<A> list1 = Arrays.asList(new B(), new B1(), new B2());
2.        List<A> list2 = new ArrayList<A>();
3.        Collections.addAll(list2, new C1(), new C2());
4.        List<A> list3 = Arrays.asList(new C1(), new C2());
    }
}
Explanation
The call to Arrays.asList() while trying to initialize list3 creates List<B> instead of List<A>. The call to Collections.addAll() does not cause a compiler error because the target type is inferred from its first argument.

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
Java quizzes
Cosmo
Sign Up Now
or Subscribe for future quizzes