Weird Integer boxing in Java

前端 未结 12 1901
广开言路
广开言路 2020-11-22 00:15

I just saw code similar to this:

public class Scratch
{
    public static void main(String[] args)
    {
        Integer a = 1000, b = 1000;
        System.o         


        
12条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 00:47

    Yes, there is a strange autoboxing rule that kicks in when the values are in a certain range. When you assign a constant to an Object variable, nothing in the language definition says a new object must be created. It may reuse an existing object from cache.

    In fact, the JVM will usually store a cache of small Integers for this purpose, as well as values such as Boolean.TRUE and Boolean.FALSE.

提交回复
热议问题