I want to be able to make a list like so -
List<Object> l = new ArrayList<String>();
The standard library implementation of ArrayList
does not allow this. It gives compile time error. So I am writing my own implementation of the ArrayList
.
So far I have tried this -
public class ArrayList<Y extends X> implements List<X> {...}
public class ArrayList<X super Y> implements List<X> {...}
which do not compile.
So, how can I write an ArrayList where I would be able to use it like I mentioned above?
List<Object> l = new ArrayList<String>();
People have pointed out this post Is List<Dog> a subclass of List<Animal>? Why aren't Java's generics implicitly polymorphic?
But I still don't understand. The reason given was that we want to avoid situations like so -
List<Object> l = new ArrayList<String>();
l.add(new Dog());
While this makes sense, I can do a similar kind of thing with Java Arrays which compiles but throws Exception at runtime.
Object o[] = new String[10];
o[0] = new Dog();
So what is the rationale behind allowing the latter code to compile but not the former?
EDIT - Similar question has already been asked as indicated above. This question also helps Why is the ArrayStoreException a RuntimeException?