1
    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?

Spurdow
  • 2,025
  • 18
  • 22

1 Answers1

7

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
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • So that means i could something like this? Person p = new Person(); Employee extends Person Doctor extends Person ... list.add... .. Person p = list.get(0); if( p instanceof Doctor) { //i can get the doctor object? } – Spurdow Oct 08 '13 at 17:59
  • by the way thanks for the clear explaination, i thought i cant do it like that.. theres a reason why i need to know how to do it like that – Spurdow Oct 08 '13 at 18:05
  • @GriffeyDog. `List>` is rarely useful, because you can't add anything into it except `null`. Well, you can't add anything to `List extends Object>` too. Those kinds of declared type are often used as formal parameter types, where you might want to send different concrete instantiation of `List`. – Rohit Jain Oct 08 '13 at 18:11