Identify the bug in the following code snippet that attempts to add elements to a List of Lists using wildcards. Explain why it's incorrect.

Java interview question for Advanced practice.

Answer

The problem is that listOfLists.get(0) returns an object of type List<?. Because the compiler doesn't know the list's actual type, it prohibits calling any method like add that modifies the list to ensure type safety.

Explanation

Option B is correct. When you retrieve an element from listOfLists, its type is List<?. The ? signifies an unknown type. To preserve type safety, the Java compiler will not allow you to add any element (except null) to a collection with an unbounded wildcard, because it cannot verify if the element is of the correct unknown type. Therefore, the call to .add("world") results in a compile-time error. Option A is incorrect because the code does not compile. Option C is irrelevant to the type safety issue. Option D is incorrect as the error is caught at compile time.

Related Questions