0

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?

guy777
  • 21
  • 3
  • 1
    [Why are arrays covariant but generics are invariant?](https://stackoverflow.com/q/18666710), [Is List a subclass of List? Why are Java generics not implicitly polymorphic?](https://stackoverflow.com/q/2745265) – Pshemo Oct 06 '20 at 18:16
  • 1
    Completely unrelated, yet important: the `Integer` constructor is deprecated in newer Java versions. Use `valueOf` instead. This also leverages the Integer cache. – MC Emperor Oct 06 '20 at 19:01

0 Answers0