java中 gt 是什么,<>的含义是什么? Java中的令牌?

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 >

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值