Should autoboxing be avoided in Java?

前端 未结 5 1554
谎友^
谎友^ 2021-01-17 12:51

There are instances where a method expects a primitive type double and you pass a Double object as a parameter.

Since the compiler unboxes

5条回答
  •  终归单人心
    2021-01-17 13:46

    This is what Java Notes says on autoboxing:

    Prefer primitive types

    Use the primitive types where there is no need for objects for two reasons.

    1. Primitive types may be a lot faster than the corresponding wrapper types, and are never slower.
    2. The immutability (can't be changed after creation) of the wrapper types may make their use impossible.
    3. There can be some unexpected behavior involving == (compare references) and .equals() (compare values). See the reference below for examples.

提交回复
热议问题