When adding an integer to ArrayList

后端 未结 3 1776
走了就别回头了
走了就别回头了 2021-01-15 20:50

I have a very stupid question here. When we add an int value to an ArrayList, will it create a new Integer object of that int value? For example:

int a = 1;
         


        
相关标签:
3条回答
  • 2021-01-15 21:21

    Whether a new Integer object is created depends on the value if the int being added. The JVM has a cache of premade objects covering a range of common values, and if the value is in that range it will use the existing cached object instead of creating a new one.

    For the int type, the Java language specification requires that this cache cover all numbers from -128 to 127 (inclusive). A JVM implementation may or may not include additional values in this cache, at its option.

    0 讨论(0)
  • 2021-01-15 21:26

    The a is autoboxed to an Integer. From the link,

    Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.

    0 讨论(0)
  • 2021-01-15 21:40

    In

    int a = 1;
    ArrayList<Integer> list = new ArrayList<Integer>();
    list.add(a);
    

    the last line is automatically converted by the compiler into:

    list.add(Integer.valueOf(a));
    

    Integer.valueOf is a method that either creates a new Integer object with the same value, or reuses one that already exists. The resulting object has no relation to the variable a, except that it represents the same value.

    0 讨论(0)
提交回复
热议问题