Practice mode Java

Why does List<Object> y = new ArrayList<String>(); fail to compile in Java?

Correct answer B. Generic types are invariant in their type argument

Explanation

Although String is a subtype of Object, List is not a subtype of List. If it were, code could add an Integer through the Object view and corrupt a list of strings. Generics therefore forbid this at compile time, unlike covariant arrays, and a wildcard such as List gives a safe read-only view.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.