Why doesn't Java autoboxing extend to method invocations of methods of the autoboxed types?

前端 未结 8 1031
时光取名叫无心
时光取名叫无心 2020-12-30 18:19

I want to convert a primitive to a string, and I tried:

myInt.toString();

This fails with the error:

int cannot be derefere         


        
8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-30 19:00

    The valid syntax closest to your example is

    ((Integer) myInt).toString();
    

    When the compiler finishes, that's equivalent to

    Integer.valueOf(myInt).toString();
    

    However, this doesn't perform as well as the conventional usage, String.valueOf(myInt), because, except in special cases, it creates a new Integer instance, then immediately throws it away, resulting in more unnecessary garbage. (A small range of integers are cached, and access by an array access.) Perhaps language designers wanted to discourage this usage for performance reasons.

    Edit: I'd appreciate it if the downvoter(s) would comment about why this is not helpful.

提交回复
热议问题