简体   繁体   中英

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. 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.

Above scenario is considered for a class which is implementing Comparable interface.

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. E need not extend String(any other class).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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