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>
?
source to share
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.
source to share