S
S
Sergey2017-07-20 18:48:30
Java
Sergey, 2017-07-20 18:48:30

Why can't you use primitive types in generic classes/methods?

Hello.
We have this code:

private static <T> T testAutoboxing(T obj)
{
    return obj;
}

public static void main(String[] argv)
{
    System.out.println(Learn.<int>testAutoboxing(5));
}

During type erasure, int becomes Object, and the value 5 can be equated to Object using autoboxing.
The question itself is: why is it forbidden to use primitive types in this case, if they have autoboxing, and why does it not work?
PS I read the documentation, I read the book and I know how reference types differ from primitives. The question may be elementary, but I'm a beginner with a week of experience. It is only unclear why, having declared a primitive, the compiler does not convert it into a shell, and there you can push it into Object, as happens with other reference types. Or is there a fundamental separation of primitives from objects of any class?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
U
Ulyan Romanov, 2017-07-20
@TexxTyRe

The book only confronts the fact that only reference types can be specified. If you want primitive, then you need to resort to encapsulation.

M
Maxim Moseychuk, 2017-07-21
@fshp

During type erasure, int will become Object,

No. Where did you get it from? For primitives, types are not erased.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question