5

I saw that definition in a protobuf generated java file:

java.util.List<? extends xxx.yyy.zzz.proto.BasicMessage.DestInfoOrBuilder> foo();

But what dose <? and extends mean? I can understand List<SomeClass> I can't understand List<? extends SomeClass>..

lospejos
  • 1,976
  • 3
  • 19
  • 35
Sayakiss
  • 6,878
  • 8
  • 61
  • 107
  • see [java se tutorials](http://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html) – aim Dec 30 '13 at 08:20
  • 1
    The parameter type should by a subtype of `SomeClass` – Paul Samsotha Dec 30 '13 at 08:20
  • I tried to explain it in my answer to http://stackoverflow.com/questions/20037561/assigning-a-generic-list-to-a-concrete-arraylist-is-causing-a-compile-time-error – Dawood ibn Kareem Dec 30 '13 at 08:25
  • 1
    Have a look [here](http://stackoverflow.com/questions/252055/java-generics-wildcards) for an explaination of upper bounded and lower bounded wildcards. There are some links to the Java tuts too. – Steve Benett Dec 30 '13 at 08:25
  • This will help . http://www.thejavageek.com/2013/08/28/generics-the-wildcard-operator/ – Prasad Kharkar Dec 30 '13 at 08:28

3 Answers3

12

In java generics programing, there are two kinds of bounds when using wildcards.

1)Upper Bounded Wildcards . like: ArrayList <? extends Number> p, it means you can use anything extends Number to fill the ArrayList.

2)Lower Bounded Wildcards. like:ArrayList<? super Integer> list, it means you will have to pass anything which is in the super class (such as Number, Object)of Integer to fill the ArrayList.

for more information, refer to wildcards.

wangdq
  • 1,874
  • 17
  • 26
3

This is a generic declaration.

It is used to check types at compile time. You could put any object into a list, but that would make it more difficult to maintain and could cause ClassCastExceptions, if not used appropriate.

<? extends xxx.yyy.zzz.proto.BasicMessage.DestInfoOrBuilder> means "allow every class which extends DestInfoOrBuilder".

Christian Strempfer
  • 7,291
  • 6
  • 50
  • 75
2

In java generic code, the question mark (?), called the wildcard, represents an unknown type. The wildcard can be used in a variety of situations: as the type of a parameter, field, or local variable; sometimes as a return type (though it is better programming practice to be more specific). The wildcard is never used as a type argument for a generic method invocation, a generic class instance creation, or a supertype.

For more information read Java Generic's Wildcards and Generics: The wildcard operator

rachana
  • 3,344
  • 7
  • 30
  • 49