Generics types must be the same. Period. You can't do this:
List<Number> = new ArrayList<Integer>();
It only works with
List <Number> = new ArrayList<Number>();
or
List<Integer> = new ArrayList<Integer>();
It might be strange because you CAN do it with arrays:
Number[] num = new Integer[5];
Well, the explanation is a little long, but short: Generics verification only occurs at compiling time. At runtime,
java use these classes as if they were no generic restriction. Array does use types at runtime.
So, why is it important?
What happens if I do this?
List <Number> = new ArrayList<Integer>;
List.add(new Float(2.1));
See what happened? It should be legal, but it is wrong. At runtime, java won't notice it when you add it, but it will explode when you retrieve it.
When you use wildcard using extends, you're saying that you won't add anything to the list, so you can assign it. By the way, you can add items if you're using wildcard with super, just think about why.
Test what happens using arrays:
Number [] num = new Integer[4];
num[0] = new Float (2.1);
It will explode at runtime!
[ May 24, 2008: Message edited by: Daniel Del Moral ]
[ May 24, 2008: Message edited by: Daniel Del Moral ]