Nikhil Pujari wrote:@ravi: Explicit casting works, but I wonder why I need it. It seems redundant.
In my opinion, if you are using generics,
you should not be explicitly casting. It is not redundant. If the compiler is complaining, it is because they compoler considers it not safe. If you override the compiler by explicitly casting, at best, you are not letting the compiler do its job. And at worst, you are wrong (and the compiler is right) and you may have broken something in your program.
As for your example....
A List<? extends Number> is *NOT* assignable to a List<Integer>, hence, the compiler error.
A List<? extends Number> is *NOT* assignable to a List<Number>, hence, the compiler error.
Now again, for your example, your method is returning a List<Number>, so with your explicit casting...
The first line of the example is actually broken, it is trying to assign a List<Number> to a List<Integer>, which is *NOT* type safe. From within the method, it is possible to put Number types that is not Integer into the list, which you then explicit cast to List<Integer>. So, in the first cast, you were wrong, and the compiler right, and you could have broken something.
Henry