This is a small snippet of code taken from some of the examples that accompany the Stanford Parser. I've been developing in Java for about 4 years, but have never had a very strong understanding of what this style of code is supposed to indicate.
List<? extends HasWord> wordList = toke.tokenize();
I'm not worried about the details of the code. What I'm confused about is what exactly the generic expression is supposed to convey, in English.
Can someone explain this to me?
In English:
It's a
List
of some type that extends the classHasWord
, includingHasWord
In general the ?
in generics means any class. And the extends SomeClass
specifies that that object must extend SomeClass
(or be that class).
List<? extends HasWord>
accepts any concrete classes that extends HasWord. If you have the following classes...
public class A extends HasWord { .. }
public class B extends HasWord { .. }
public class C { .. }
public class D extends SomeOtherWord { .. }
... the wordList
can ONLY contain a list of either As or Bs or mixture of both because both classes extend the same parent or null
(which fails instanceof checks for HasWorld
).
A question mark is a signifier for 'any type'. ?
alone means
Any type extending
Object
(includingObject
)
while your example above means
Any type extending or implementing
HasWord
(includingHasWord
ifHasWord
is a non-abstract class)
Perhaps a contrived "real world" example would help.
At my place of work we have rubbish bins that come in different flavours. All bins contain rubbish, but some bins are specialist and do not take all types of rubbish. So we have Bin<CupRubbish>
and Bin<RecylcableRubbish>
. The type system needs to make sure I can't put my HalfEatenSandwichRubbish
into either of these types, but it can go into a general rubbish bin Bin<Rubbish>
. If I wanted to talk about a Bin
of Rubbish
which may be specialised so I can't put in incompatible rubbish, then that would be Bin<? extends Rubbish>
.
(Note: ? extends
does not mean read-only. For instance, I can with proper precautions take out a piece of rubbish from a bin of unknown speciality and later put it back in a different place.)
Not sure how much that helps. Pointer-to-pointer in presence of polymorphism isn't entirely obvious.
The question mark is used to define wildcards. Checkout the Oracle documentation about them: http://docs.oracle.com/javase/tutorial/java/generics/wildcards.html
Source: Stackoverflow.com