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

前端 未结 8 1797
囚心锁ツ
囚心锁ツ 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:27

    The joker ? can hold any type. If you want to use the same type for all methods/members you can make the whole class generic. By writing StopAlarmTask<T> you define the type T in the whole class.

    private final class StopAlarmTask<T> implements Runnable 
    {
        StopAlarmTask(ScheduledFuture<T> aSchedFuture)
        {
            fSchedFuture = aSchedFuture;
        }
    
        public void run() 
        { /* */ }
    
        private ScheduledFuture<T> fSchedFuture;
    }
    
    0 讨论(0)
  • 2020-12-18 02:30

    Assuming this.executorService is a subtype of ScheduledExecutorService (available since Java 1.5), the return type of scheduleWithFixedDelay() is ScheduledFuture<?>. You can't change the return type from ScheduledFuture<?> to ScheduledFuture<T>, ScheduledFuture<Integer> or anything else for that matter. You could, however, change it to just ScheduledFuture since <?> is a wildcard generic type parameter that approximates a raw type for backward compatibility.

    See What is a raw type and why shouldn't we use it? for a good discussion on raw types and generics.

    0 讨论(0)
提交回复
热议问题