Question

I have a parameterized generic class X which takes a type T. On which no conditions (like T extends/implements) have been defined.

class X <T> {
    Map<T, String> map = new HashMap<T, String>();

    public void put() {
        map.put((T)getLong(), "");
    }

    public long getLong() {
        return 0L;
    }
}

We know that T is definitely an object type and not a primitive. So I'd expect the returned "long" value to be Autoboxed to Long and then the cast to T would follow, but that doesn't happen.

Compiler says "Cannot cast from long to T". If I replace the parameterized type T with "Long", there's no problem. Can anyone explain why Java doesn't support autoboxing of primitive types when a parameterized type is involved ? Is there something I am missing ?

Thanks!

Was it helpful?

Solution

I think , first you should autobox then cast to T. It should be written as follows.

public Long getLong() {  //not long, because it's primitive
        return 0L;
    }

So autoboxing happens when this method returns. What happens in your case is, it doesn't autobox long primitive and you trying to cast this long primitive to T. that you simply can't do.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top