Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

generics - What is the meaning of the <?> token in 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 <T> 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 <T> 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 <T>, it has to appear in the class declaration. Here there is no <T> nor <?> in the class declaration but it still compiles and runs properly.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 >

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...