Generic
types in Java are invariant. That means, if T2 is a subtype of T1,
List<T2> is not a sub type of List<T1>.
Ex
Integer
is a subtype of Number.
But
Stack<Integer> is not a sub type of Stack<Number>.
Why java makes
generics as invariant?
Let
me explain with an example.
/* Define a character list */ List<Character> chars = new ArrayList<Character>(); /* Java do not allow this */ List<Object> objs = chars; /* Adding double to character list */ objs.add(1.23); /* ClassCastException: Cannot cast double to Character */ Character s = chars.get(0);
As
you notify above snippet. I defined a character list ‘chars’ and cast it to
list of objects ‘objs’. I added a double to ‘objs’. Last statement cast the
double to character, which is not possible. To prohibit these kind of things
and ensure run time safety of the application, java generics are invariant.
You may like
No comments:
Post a Comment