I am trying to understand the difference between static and non-static generic methods in Java:
public class Pair<K, V> {
private K key;
private V value;
//the type of the _this_ object and the argument should be the same (just like in scompare)?
public <X, Y> boolean compare(Pair<X, Y> p2) {
return key.equals(key) && value.equals(value);
}
public static <N, M> boolean scompare(Pair<N, M> v1, Pair<N, M> v2) {
return v1.key.equals(v2.key) && v1.value.equals(v2.value);
}
}
Other than the fact that scompare is static, the behavior should not be different. What I find strange is the following:
Pair<Integer, String> p1 = new Pair<>(1, "apple");
Pair<Integer, Integer> e1 = new Pair<>(4, 3);
//causes compile-time error (as it should)
System.out.println("e1 scompare p1: " + Pair.scompare(e1, p1));
//no compile-time error --- why?
System.out.println("e1 compare p1: " + e1.compare(p1));
The compile-time error is that one argument is of type Pair<Integer,Integer>
and the other is of type Pair<Integer,String>
.
So my question is: why does e1.compare(p1)
not cause a compile-time error?
Files for this MWE:
Pair.java: https://pastebin.com/rmY9M0gk
D1.java: https://pastebin.com/1MpvPXBC
[Platform:
javac 1.8.0_151
openjdk version "1.8.0_151"
]