I'm trying to understand generics, but I block at wildcard bounds and casts. For instance:
List<? extends Number> l = new ArrayList<>();
List<PositiveInteger> p = new ArrayList<PositiveInteger>();
p.add(new PositiveInteger(10));
l = p;
NegativeInteger ni = (NegativeInteger) l.get(0);// runtime java.lang.ClassCastException:
System.out.println(ni);
NegativeNumber and PositiveNumber both extend Number. So the question is why there is no warning at compile-time when casting the element from the list into a NegativeNumber ? Is there a way to prevent this type of exception ?