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

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

    A letter in brackets like would be a type parameter. You would say class StopAlarmTask to mean that you are parameterizing the type StopAlarmTask with the type T. The type parameter T would become a part of the type, sort of like a constructor argument becomes part of a new instance.

    Then, whenever you declared a StopAlarmTask, you would provide a type, e.g. String, to fill in the type parameter T. You could then refer to that type parameter within the class body. For example, you could define methods which take a T or return a T, or parameterize member variables like fSchedFuture with T. For example, if you parameterized a declaration of StopAlarmTask as StopAlarmTask, then String would be captured as T and wherever you used T within that StopAlarmTask it would act as String.

    However, in the code you have listed, StopAlarmTask does not have a type parameter and cannot be parameterized with any type. There is no captured type to refer to as T within the class body.

    On the other hand, means "I don't know which type it will be; I don't even know that it will be the type that someone has used to parameterize StopAlarmTask."

    You could have parameterized StopAlarmTask, and in that case you could have two variables:

    private ScheduledFuture fSchedFuture1;
    private ScheduledFuture fSchedFuture2;
    

    The first declaration says that the type parameter of the ScheduledFuture is the same as the type parameter of the enclosing StopAlarmTask. E.g. StopAlarmTask would make fSchedFuture1 into a ScheduledFuture. The second declaration says that we don't know what the type parameter of the ScheduledFuture is, even if we know the type parameter of the enclosing StopAlarmTask.

提交回复
热议问题