Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Diamond Not compiling Java 7 [duplicate]

Tags:

java

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

like image 278
soufiane fahid Avatar asked Oct 28 '15 15:10

soufiane fahid


1 Answers

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 !

like image 125
Florian Avatar answered Oct 30 '22 18:10

Florian