It seems either this concept is not straight forward to understand, or the so many long articles on the web are not really explaining well. I appreciate if someone can explain in a clear and short way.
I have read the examples in this blog and this video.
The conclusion I draw so far is:
In Java, arrays are covariant and generics are invariant.
Arrays are covariant:
Number[] myNums = new Integer[3]; // compile ok
but.. if I do this, run time error though compile ok:
myNums[0] = 2.1; // compile ok, run time not ok
What is the point of having array covariant if run time will be NOT ok? This question may actually refer to "What's the point of covariant?"
Generics are invariant:
List<Number> myNums = new ArrayList<Integer>(); // compile not ok
But amazingly, there's a way to make generics covariant/cotravariant, use wildcard:
List<? extends Number> myNums1 = new ArrayList<Integer>(); // convariance, compile ok List<? super Integer> myNums2 = new ArrayList<Number>(); // contravariance, compile ok
Even there's the way to make it covariant or contravariant, I still cannot do things like
myNums1.add(New Integer(1));
What is the point of all of this?
Please, is there anyone help me to clear out all this confusion?