9

I have seen some code as follows

public interface IBean {

}

and its usage at some places as

public void persist(List<? extends IBean> beansList) {

}

However same can achieved with following code

public void persist(List<IBean> beansList) {

}

So what is the difference between both methods, both are excepting objects that must inherit IBean interface?

Here are the bean classes

public class Category implement IBean {
  //related fields
}

public class Product implement IBean {
  //related fields
}
Eran
  • 387,369
  • 54
  • 702
  • 768
PHP Avenger
  • 1,744
  • 6
  • 37
  • 66

2 Answers2

5

You can pass a List<Category> to public void persist(List<? extends IBean> beansList), but you cannot pass a List<Category> to public void persist(List<IBean> beansList).

On the other hand, you can pass a List<IBean> to both methods.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • 1
    Your are right, but why? Category is an IBean, so it should accept it? or rules are different when we use generics like List> – PHP Avenger Oct 19 '16 at 06:33
  • 1
    @PHPAvenger `List` is not a sub-interface of `List`. A `List` may only contain `Category` instances (or instances of sub-classes of `Category`) while a `List` may also contain `Product` instances. – Eran Oct 19 '16 at 06:35
  • Bravo, Now that make sense – PHP Avenger Oct 19 '16 at 06:36
4

The reason is that generics are invariant. This means for example that you can't use a List<Integer> where a List<Number> is expected.

But when turning to wildcards, you can circumvent that restriction. Therefore, when you really have a List<Product> you will not be able to pass that into a method that expects List<IBean> - you would have to somehow convert the list first. To be precise: you would do a "hard" cast; as there is no point in "converting" generic lists, as type erasure kicks in at runtime anyway!

By using the wildcard on the method definition, you can allow for passing Lists that use "real" sub classes of the extended type; without the need of ugly casts.

GhostCat
  • 137,827
  • 25
  • 176
  • 248