简体   繁体   English

Java泛型,类型变量范围

[英]Java generics, type variable scope

What's the difference between: 之间有什么区别:

public <E>int  compareTo(E e) // first line (compilation error)

and

public int compareTo(E e) // second line (OK)

only in the second line i get through the compiler. 仅在第二行中,我通过了编译器。 Does it mean that it needs to be sure that that particular element is universally declared within the class? 这是否意味着需要确保该特定元素在类中被通用声明? Otherwise you could put in any element and would not make much sense. 否则,您可以添加任何元素,并且没有任何意义。 Am I seeing it in the right way? 我是否以正确的方式看到它? Thanks in advance. 提前致谢。

Put the type parameter declaration before the return type: 将类型参数声明放在返回类型之前:

public <E> int compareTo(E e) 

You can have a class level <E> type parameter as well, but the method level parameter will shadow it. 您也可以具有一个类级别的<E>类型参数,但是方法级别的参数将使其阴影。 Read more about it in this question . 阅读更多有关此问题的信息

public <E extends String> int compareTo(E o) {  //1
}

You can consider any class instead of String as per your programming need. 您可以根据编程需要考虑使用任何类而不是String

Above scenario is considered for a class which is implementing Comparable interface. 对于正在实现Comparable接口的类,考虑以上情形。

class SimpleClass<E> {  // 2
    E var;  
    public <E> int compareTo(E o) {         
        return 0;
    }
}

above class at //2 will work if we don't implement Comparable interface. 如果不实现Comparable接口,则// 2处的上述类将起作用。 E need not extend String(any other class). E不需要扩展String(任何其他类)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM