I have defined the following generic Class , But when I use it on the Class Object it doesn't compile. The constructor wouldn't accept other object
class Pair<T,V> {
T one;
V two;
public Pair(T one, V two) {
this.one = one;
this.two = two;
}
}
public static void main(String[] args) {
String hamza = "Hamza";
Integer soufiane = 0;
Pair<Object,Object> pairOne = new Pair<>(hamza, soufiane);
Pair<Object,Object> pairTwo = new Pair<Object, Object>(soufiane, hamza);
}
Error message:
incompatible types: Pair<String,Integer> cannot be converted to Pair<Object,Object>
Why did the first one not Compile and the second compile ?
EDIT: It compiled on Java 8
Your code fail because the java 7 compiler can't find the proper inferred type; on the other hand java 8 would compile and work fine. (tl;dr: java 7 doesn't properly works with all diamonds, this was improved in java 8)
JEP 101: Generalized Target-Type Inference
Smoothly expand the scope of method type-inference to support (i) inference in method context and (ii) inference in chained calls.
Meaning java 8 would be able to determine the type of your call using the diamond operator.
EDIT: Looks like someone beat me to this reponse in the thread and explained it more clearly than me; so take a look !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With