Diamond Does Not Compile Java 7

I have defined the following general class, but when I use it in a class object, it does not compile. The constructor will not accept another 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 didn't the first compile and the second compile?

EDIT: It compiled in Java 8

+6
source share
1 answer

Your code error because the java 7 compiler cannot find the correct output type; on the other hand, java 8 will compile and work fine. (tl; dr: java 7 does not work correctly with all diamonds, this improved in java 8)

JEP 101: Generic Output of the Target Type

Extend the scope of the output method to support (i) output in the context of the method and (ii) output in the call chain.

A java value of 8 will determine the type of your call using the diamond operator.

EDIT: It seems that someone beat me to this answer in the subject and explained it more clearly than I did; so take a look!

+3
source

All Articles