Hello,
I came across this question in Inquisition (John Meyer) and the explanation is a bit questionable to me.
This is the code:
public static void main( String args[] )
{
List<? extends Number> type = new ArrayList<Integer>(); // 1
for ( Integer n : type ) // 2
{
System.out.println(n); // 3
}
}
public <T> void seth(List<?> type) // 4
{
type.add("hi"); // 5
}
The answer says
"Lines 2 and 5 have compilation errors". with the following explanation:
You can't add anything to a List reference that has a "?" ( unless it has a super keyword followed by a class name ) and type in main() has to be referenced by a Number not an Integer. So the for in loop fails to compile.
But I think it is lines 1 and 5.
Because line-1 cannot compile. I tried it and gave an
"incompatible types" error. And also this is one of the most stressed out points in the K&B book. The reference type and the object type MUST BE THE SAME.
So there is no way "List<? extends Number> type = new ArrayList<Integer>();" can compile in my understanding.
Am I getting this wrong or there is a mistake in the question?
Thank you.