What is the meaning of the > token in this code copied from www.JavaPractices.com? When I replace it with the more conventional looking used for generic types, it fails to compile. (Error: T cannot be resolved to a type.) Why?
// > occurs 3 times in the entire program. When it is replaced with the
// program no longer compiles.
void activateAlarmThenStop()
{
Runnable myPeriodicTask = new PeriodicTask();
ScheduledFuture> soundAlarmFuture =
this.executorService.scheduleWithFixedDelay(myPeriodicTask,
startT,
period,
TimeUnit.SECONDS
);
Runnable stopAlarm = new StopAlarmTask(soundAlarmFuture);
this.executorService.schedule(stopAlarm, stopT, TimeUnit.SECONDS);
}
private final class StopAlarmTask implements Runnable
{
StopAlarmTask(ScheduledFuture> aSchedFuture)
{
fSchedFuture = aSchedFuture;
}
public void run()
{
CConsole.pw.println("Stopping alarm.");
fSchedFuture.cancel(doNotInterruptIfRunningFlag);
executorService.shutdown();
}
private ScheduledFuture> fSchedFuture;
}
Edit: Of course when we use generic type tokens like , it has to appear in the class declaration. Here there is no nor > in the class declaration but it still compiles and runs properly.
解决方案
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:
make StopAlarmTask generic (there is no sense in this case)
use concrete type in ScheduledFuture, but then it would be only one possible result type, for example String or Integer
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 >