-1

I looked for an explanation on my java book, but I dind't find it. I'm looking for an article on the internet, but I'm not finding anything clear.

Does Collection <? extends myObject> means that I can put in the Collection both myObject and objects that extend myObject? Does it means anything else?

MDP
  • 4,177
  • 21
  • 63
  • 119

3 Answers3

2

it means any object can replace ? that is a-kind-of relationship or sub class of myObject, where myObject can be class or interface

For example:

class Doctor{}

class GeneralDoctor extends Doctor{}

class Dentist extends Doctor{}

Then, Collection<? extends Doctor> doctors; will accept only children of Doctor (ie. either GeneralDoctor or Dentist)

Sridhar
  • 1,832
  • 3
  • 23
  • 44
1

Does Collection <? extends myObject> mean that I can put in the Collection both myObject and objects that extend myObject?

Not really - it means that the collection is a collection of some specific type that extends myObject. To take a clearer example, if you have a Collection<? extends Number> it could be a Collection<Integer> or maybe a Collection<Double> or maybe a Collection<Number> but you don't know which.

As a consequence you can't add anything to that collection because you don't know what its generic type is. However if you get an element from that collection you can be assured that it is a Number.

List<? extends Number> c = getList();
Number n = c.get(0); //ok
c.add(1); //not ok, c could well be a List<BigDecimal>, we don't know
assylias
  • 321,522
  • 82
  • 660
  • 783
  • Thank for the clear explanation. If you have time, I have another question. If I can't do c.add(1), this means that I can't create programmatically a Collection and then fill it. Does this mean that I can use extends Number> just as an argument of a method? – MDP Jan 08 '15 at 09:26
  • 1
    You can use it where you don't need to know the exact type of the collection. But typically you'd use it when a method returns that type (say, based on my example: `public Collection extends Number> getList() {...}`). – assylias Jan 08 '15 at 10:46
1

It is called a generic method. This whole concept is called "Generics" in Java. That declaration means T can be any type that is subclass of myObject

abdotalaat
  • 735
  • 7
  • 10