Jizhou Zhang
Jizhou Zhang

Reputation: 87

Gneric type in Java about what is the actual return type?

Here is a snippet code of generic class in Java

public class PairTest{
    public static void main(String[] args){
        LocalDate[] birthdays = {....}    // initialize birthdays array
        Pair<LocalDate> mm = ArrayAlg.minmax(birthdays); // THIS LINE !
    }
}

public ArrayAlg{
    public static < T extends Comparable> Pair<T> minmax(T[] a){
        T min = a[0];
        T max = a[0];
        for(int i = 0; i < a.length; i++){
            if(min.compareTo(a[i] > 0) min = a[i];
            if(max.compareTo(a[i] < 0) max = a[i];
        }
        return new Pair<>(min,max);
    }
}

my question is, the line commented as THIS LINE ! does tell what generic type for static method minmax, so I should interpret this line as Pair<LocalDate> mm = ArrayAlg.<LocalDate>minmax(birthdays);.

Or the generic method type is based on the parameter type I pass into which is 'a', for example, if ArrayAlg.minmax(SubOfLocalDate[] a), it returns new Pair<SubOfLocalDate> (min, max) for that static method.

Upvotes: 0

Views: 82

Answers (2)

M A
M A

Reputation: 72884

If your question is on what basis the compiler infered the type argument of the generic method, then yes it's based on the declared type of the method argument birthdays which is of type LocalDate[]. The type parameter T is therefore bound to LocalDate (which implements Comparable so it matches the upper bound of T).

Note that in this case the compiler does not need to check the declared type of the assigned variable mm to determine the bound type argument. If the assigned variable is declared with another type, i.e. if mm were of type Pair<SomeOtherType>, the compiler would generate an error.

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533730

At runtime

public static <T extends Comparable<T>> Pair<T> minmax(T[] a) {

becomes with type erasure

public static Pair<Comparable> minmax(Comparable[] a) {

and

Pair<LocalDate> mm = ArrayAlg.minmax(birthdays); 

is actually just

Pair mm = ArrayAlg.minmax(birthdays); 

Upvotes: 2

Related Questions