Autoboxing

ArrayLists

Autoboxing

🙋 Need help? Ask an expert now!

"Autoboxing" is a way to work with primitive data types within ArrayLists to make your coding easier. If we wanted to create an ArrayList of integers, we use ArrayList<Integer> because int is not an object. However, when we call methods such as add() and set(), instead of creating a new object add(new Integer(11));, we can just write add(11) as Java automatically converts int into Integer for us. Look below for an example of autoboxing.

AutoBoxingExample.java
package exlcode;

import java.util.ArrayList;

public class AutoBoxingExample {

  public static ArrayList exampleVariableOne = new ArrayList();

  public static void main(String[] args) {
    exampleVariableOne.add(new Integer(5));
    // autoboxing leads to simple code without unnecessary boxing
    exampleVariableOne.add(80);
    System.out.println(exampleVariableOne);
  }
}

Autoboxing automatically converts int values to type Integer when the program is run. Therefore, regardless of what primitive data type we want to use, as long as we initialize the ArrayList with the right object, we can add primitive data types without creating new objects.

Use autoboxing when creating an ArrayList of objects that have corresponding primitive data types. It makes coding a lot more simple when debugging the code.

Edit Me on GitHub!

Application Question

Consider the following code segment:

ArrayList<Integer> varOne = new ArrayList<Integer>();
varOne.add(new Integer(1));
varOne.add(new Integer(2));
varOne.add(new Integer(3));
varOne.set(2, new Integer(4));
varOne.add(2, new Integer(5));
varOne.add(new Integer(6));
System.out.println(varOne);

What is printed as a result of executing the code segment?