Java - Why is generic subtyping not allowed but subtyping of arrays is allowed

64 views Asked by At

In java generic subtyping is not allowed which means this will not work -

List<String> ls = new ArrayList<String>(); 
List<Object> lo = ls;

That is so that things like this can't be carried out and would not cause run time errors -

lo.add(new Object());
String s = ls.get(0); 

But then if you tried -

String a[] = {"see","biscuit","teleport"};
Object b [] = a;

It would work even though arrays would still be affected by the same problem of possible run time errors -

b[0] = new Integer(33);

That would throw an ArrayStoreException at runtime. My question is is there a particular reason why sub typing is allowed with arrays but not generics or this is just a fault that can be fixed by stopping array sub typing from working?

0

There are 0 answers