Using generics for the first time I stumbled upon this basic situation:
ArrayList<Number> arrayList = new ArrayList<Integer>(); //compile error
Number number = arrayList.get(0);
...then I found the correct syntax to make it work:
ArrayList<? extends Number> arrayList = new ArrayList<Integer>(); //correct
Number number = arrayList.get(0);
...that because there is a lower bound feature and the "extends" and "super"keyworks is needed to differentiate between them:
ArrayList<? super Integer> arrayList = new ArrayList<Number>();
Object number = arrayList.get(0); //returns java.lang.Object
...which has the same effect as:
ArrayList arrayList = new ArrayList();
Object number = arrayList.get(0);
...which adds nothing compared to not using generics and making lower bouds almost useless.
Of course lower bounds add an extra check and this code doesn't compile:
ArrayList<? super Number> arrayList = new ArrayList<Integer>();
Object number = arrayList.get(0);
...but does this kind of check has really any use?!
Its like wanting the following code to not compile:
Number number = new Integer(0);
...but why would anyone want that?
Defining upper bounds is necessary to check types at compile-time and avoid NoSuchMethodError to be thrown, but I found no use to lower bounds besides hampering polymorphism and making the more useful upper bound syntax more polluted.
Maybe I didn't get the idea behind lower bounds... can anyone show me some real use to it?