Why is int changed to Integer automatically in java?

前端 未结 6 1553
半阙折子戏
半阙折子戏 2021-01-16 15:12

Why is primitive type int changed to object Integer automatically when i put primitve type int to ArrayList in java?

6条回答
  •  -上瘾入骨i
    2021-01-16 15:33

    This is a java language feature that was introduced with java 1.5. It's called autoboxing.

    Roughly spoken, it converts between java primitive types to their corresponding wrapper class types. The compiler detects when inboxing (primitive-to-wrapper) or outboxing (wrapper-to-primitive) is needed (and possible) and expands the expression the correct byte code.

    So, behind the scenes, an instance of Integer is added to the list when you add an int.

提交回复
热议问题