When adding an integer to ArrayList

后端 未结 3 1914
走了就别回头了
走了就别回头了 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:40

    In

    int a = 1;
    ArrayList list = new ArrayList();
    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.

提交回复
热议问题