0

I have a question while writing code that declares a simple array and adds it to the list.

   int[] value = new int[]{1, 2, 3};
   List<Integer> arrayToList = new ArrayList<>();
   for (int number : value) {
       arrayToList.add(number);
   }

I want to know how list.add () works internally. if the "new" keyword is used for each element to create an instance. If not, I wonder if Integer.valueOf () is being used.

To summarize, each array element is a primitive type. I want to know how it works internally and converts it to a reference type.

Alex K.
  • 171,639
  • 30
  • 264
  • 288
Bo Hun Kim
  • 33
  • 4
  • Have you tried to read the source code? – dehasi Aug 02 '18 at 12:13
  • The concrete way how the `List#add(E e)` works heavily depends on the type of List we're talking about. e.g. the `ArrayList` heavily differs from the `LinkedList`. But as the name might suggest already the `ArrayList`uses a backening array to store the references. – L.Spillner Aug 02 '18 at 12:21
  • Thank you Everyone. – Bo Hun Kim Aug 03 '18 at 07:30

2 Answers2

2

It is called Autoboxing. You could learn more about how int convert to Integer from here Why is int changed to Integer automatically in java?

If you want to know exactly happened in ArrayList.add, you could see source code from here http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/tip/src/share/classes/java/util/ArrayList.java

public boolean add(E e) {
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}
Tc Zhong
  • 452
  • 4
  • 7
  • Here another [stackoverflow answer](https://stackoverflow.com/a/22648696/8181750) that directly discusses what happens during the autoboxing (basically using `Integer.valueOf(int i)`). – L.Spillner Aug 02 '18 at 12:38
-2

add method accpets object as an input. its a super class. So autoboxing or unboxing is not required,whatever the wrapper class object you pass it will get added to the list.

  • Autoboxing is nothing you 'require'. It's something that just 'happens' when you 'cast' a primitive to it's corresponding wrapper class (like in OPs List example). Also OP didn't ask 'why' it works but 'how'. Your answer does (poorly) describe why it works. Also technically the type accepted by `List#add(E e)` depend on the generic type E. Accepting anything of type `Object` is only true if the List is used as a raw type (without type parameter) which OP did not. – L.Spillner Aug 02 '18 at 12:33