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?
Maduranga Liyanage wrote:Oops.
Sorry. Actually I have done <? super Number>. 'extends' work.
Sorry for the mistake. It compiles fine.
Would appreciate a help on the Generic method.
Well, the compiler should try to find a T, within the limits of any bounding, that will match the requirements of the parameters -- and the return type that you need. In your example, since T is not bounded, and it is not used in the paramters, you should be able to assign it to any List type that you want.