What is the meaning of the <?> token in Java?

前端 未结 8 1824
囚心锁ツ
囚心锁ツ 2020-12-18 01:47

What is the meaning of the token in this code copied from www.JavaPractices.com? When I replace it with the more conventional looking

8条回答
  •  没有蜡笔的小新
    2020-12-18 02:16

    It fails to compile, because your class is not generic (nor any of your methods). In this particular example joker (?) means that ScheduledFuture may be parametrized by anything.

    Sometimes, there is no sense to make the whole class generic if you use another generic class inside and you don't know the exact type that will be used. In this example you had three options:

    1. make StopAlarmTask generic (there is no sense in this case)
    2. use concrete type in ScheduledFuture, but then it would be only one possible result type, for example String or Integer
    3. use wildcard (< ? >) - it allows to retrieve anything as a result of FutureResult (String, Integer, your custom class). You can also narrow the scope of a possible generic type into some subclasses, for example ScheduledGeneric< ? extends MyObject > or into superclasses: ScheduledGeneric< ? super MyObject >

提交回复
热议问题