Genetic class and static generic method

I am writing a generic class

public class SomeClass<T> {

    public static <T extends Comparable<? super T>> T min(Collection<? extends T> c) {
        T min = c.iterator().next();
        for (T element : c)
            if (element.compareTo(min) < 0)
                min = element;
        return min;
    }

}

public class Main {

    public static void main(String[] args) {
        SomeClass<Integer>.min(Arrays.asList(1, 2, 3)); // compile-time error
        SomeClass.min(Arrays.asList(1, 2, 3)); // ok
    }

}

In a generic class SomeClassand generic method, is SomeMethodthe type parameter Tthe same or differentiation?

Why are we compiling a temporary error in a string SomeClass<Integer>.min(Arrays.asList(1,2,3));?

+4
source share
5 answers

Class declaration

public class SomeClass<T> 

defines a generic class where <T>the type parameter (also called a type variable) indicates. This introduces a type variable Tthat can be used anywhere within the class.

And the method declaration:

public static <T extends Comparable<? super T>> T min(Collection<? extends T> c) {
...
}

a generic method. - , . , , .

, min, :

SomeClass.<Integer>min(Arrays.asList(1,2,3));
+3

, , - . .

0

T , , T.

SomeClass<Integer> a = new SomeClass<Integer>();
a.min(Arrays.asList(1, 2, 3));

SomeClass.min(Arrays.asList(1, 2, 3));
0

T : - ( ), - . , .

SomeClass<Integer>.min(Arrays.asList(1, 2, 3));, , SomeClass, . SomeClass , , . SomeClass.<Integer>min(Arrays.asList(1, 2, 3));, , .

0

, . . . , . . , .

If you need a technical reason, this is because a method invocation expression is not one of the forms permitted by the syntax . The closest form to yours is TypeName . NonWildTypeArguments Identifier ( ArgumentListopt ). But TypeName(which is defined here ) must be an identifier or identifier corresponding to the packets. It does not allow brackets.

0
source

All Articles