What is the use of a typical return type

Please see the code below. Here in the next method, what exactly is the use of these parameters <K,V>

before the method returns?

<K, V> boolean

      

Detailed code below:

public class Util {
    // Generic static method
    public static <K, V> boolean compare(Pair<K, V> p1, Pair<K, V> p2) {
        return p1.getKey().equals(p2.getKey()) &&
               p1.getValue().equals(p2.getValue());
    }
}

      

And finally, we call it like boolean same = Util.<Integer, String>compare(p1, p2);

: is that what we should do with <Integer, String>

?

+3


source to share


2 answers


They are declarations of common type arguments used in the method.

In the same way that the keyword boolean

in front of a method name says that the method returns a Boolean value, these arguments tell that the method uses arguments of type K

and V

.



It might seem a little overkill to be listed at the beginning when they can also be seen in the method parameter list, but see Jesper's comment below.

+4


source


In this context, it is used to declare generic types to define a generic method. At run time, these types will be inferred based on the method call. This allows a certain type of security to be guaranteed. In your example, we are forcing p1 and p2 to be pairs of the same type.



+1


source







All Articles