Joker
Joker

Reputation: 11156

Assignments and Generics compilation issue

While learning Generics i found that first method that is m1 compiles successfully where as second method m2 fails to compile with following error message :

Type mismatch: cannot convert from int to Long

   class Test1 {

    <T extends Integer> void m1(T arg) {
        long i = arg;
    }

    void m2(int i) {
        Long l = i;// Compilation fails
    }
}

Can some one help me understand this behavior.

Upvotes: 0

Views: 35

Answers (2)

Endery
Endery

Reputation: 1128

You are trying to utilize autoboxing feature for assigning a primitive value to an object type. But it doesn't work if the primitive type and the wrapper object type are not of the same type. For example, if you change m2() method like this, it should work:

void m2(long i) {
    Long l = i;
}

Or you can use the valueOf() method from Long wrapper class, as already said in an answer:

void m2(int i) {
        Long l = Long.valueOf(i);
}

But I would recommend to avoid auto-boxing as much as possible. It is bad practice. You can read the article here, why it is bad: https://effective-java.com/2010/05/the-advantages-and-traps-of-autoboxing/

The last point, you should remove the extension of Integer class for the type parameter T, as Integer is a final type and cannot be extended. Then your m1() method looks like that:

void m1(Integer arg) {
        long i = arg;
}

Upvotes: 1

this is invalid

Long l = i;

because i is a primitive integer but l is an object of the type long, so that "conversion" will not happen automatically

you can get the value of that integer

Long l = Long.valueOf(i); 

note that another options related to boxing-promoting primitives can be:

void m2(int i) {
    long x = i;
    Long l = x;
}

Upvotes: 1

Related Questions