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

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

    StopAlarmTask is not a generic type.

    In the following example, you would not think Foo is a generic type.

    class Foo
    {
        Foo(int i)
        { }
    
        doStuff(List numbers)
        { }
    }
    

    The fact that the constructor of StopAlarmTask uses a generic parameter does not make the class generic any more than doStuff() makes Foo generic.

    Use to "refer to" the the declaration of a generic type in a generic way, that is, without specificity. In StopAlarmTask it just happens to be a constructor parameter. It is an "employment of" a generic type and not a declaration of a generic type because it is "merely" a parameter declaration.

    In other words, the short answer is that the parameter in the method

    StopAlarmTask(ScheduledFuture aSchedFuture)
    { ... }
    

    is applicable for all objects that are instances of ScheduledFuture for all T.

    The following is further background on generics.

    Use or or whatever to declare the generic type ScheduledFuture. Specifically, would not be used in the declaration of ScheduledFuture<> because the convention is to use a single uppercase letter.

    Note that the following test code, if fed to a compiler, will show that the first class compiles but the second does not, so to say that there is a convention to use a letter would actually be an understatement.

    class TGeneric1 {
        List list = new ArrayList();
        TGeneric1(E value) {
            this.list.add(value);
        }
        E getHead() {
            return this.list.get(0);
        }
    }
    
    class TGeneric2 {
        List list = new ArrayList();
        TGeneric2(? value) {
            this.list.add(value);
        }
        ? getHead() {
            return this.list.get(0);
        }
    }
    

    Illustrated in the following test code, there is no single letter constraint, so the following is also correct.

    class TGeneric1 {
        List list = new ArrayList();
        TGeneric1(EE value) {
            this.list.add(value);
        }
        EE getHead() {
            return this.list.get(0);
        }
    }
    

提交回复
热议问题