2

Should you use

List<ParentClass> foo = new ArrayList<ParentClass>
foo.add(ChildClassObject)

or

List<? extends ParentClass> bar - new ArrayList<ParentClass>
bar.add(ChildClassObject)

Also, could someone explain more to me the latter parameterization of List?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332

2 Answers2

4

Use the first approach. The second doesn't allow you to add any element. This is because the second approach uses an unknown type that extends ParentClass and cannot assure that the elements to be stored are from this type.

More info:

Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
3

List<? extends ParentClass> is a list of some specific subtype of ParentClass. Since, it's not know what exact specific subtype it is, the compiler won't let you add any object to it.

For starters, it's easy to mistake it with any subtype of ParentClass and wonder why they can't add the instances of the subtypes.

For instance, suppose you have a following class hierarchy -

class P { }
class A extends P { }
class B extends P { }

Now if you declare a a list as follows -

List<? extends P> l = ...;

it means l is a list of some specific subtype of P, which could be either A or B (or even P itself), but the compiler doesn't know exactly which one. So, you can't add anything to it, because the chance is that you could be adding an instance of B to a list of As creating some heap pollution.

You would declare such a list when you are only interested in reading the elements of list as P's instances.

Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142