List<? extends Object> list = new ArrayList<? extends Object>();
is there anyone that can help me out explain why cant i extend a generic to Object when using arraylist?
List<? extends Object> list = new ArrayList<? extends Object>();
is there anyone that can help me out explain why cant i extend a generic to Object when using arraylist?
why cant i super class a generic to object when using arraylist?
Because you can't instantiate a wildcard parameterized type. You can only use concrete parameterized type. It is illegal that a wildcard parameterized type appears in a new
expression.
Of course, you can use wildcard parameterized type as reference type. Think of them as interfaces. You can't instantiate an interface itself, but can use it as reference type.
So, change your declaration to:
List<? extends Object> list = new ArrayList<Object>();
But the only problem here is, you won't be able to add anything to this list. In fact, I suspect you really need this declaration of list. If you just want a list, where you can add any object of a class and any of it's subclass, then you don't need wildcard with upper bound.
For e.g, if you want to store Employee
, Doctor
, and Student
, in the same list, where all of them extend from Person
, then you can simply declare the list as:
List<Person> persons = new ArrayList<Person>();
persons.add(new Employee()); // This is OK
persons.add(new Student()); // This too is OK