3
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;

public class arraysAsList {


    public static void main(String[] args) {

        String [] arrayA = {"Box","Sun","Clock","Phone"};
        Integer [] arrayB = {21,27,24,7};

        List listStructureA = new ArrayList();
        List listStructureB = new ArrayList();

        listStructureA = Arrays.asList(arrayA);
        listStructureB = Arrays.asList(arrayB);

        System.out.println("My first list : " + listStructureA);
        System.out.println("Sun = " + listStructureA.get(1));
        System.out.println("My second list : " + listStructureB);
        System.out.println("24 = " + listStructureB.get(2));

    }

}

I realize int is a primitive type and Integer is a class. But in this script, when i try to use int instead of Integer, i get 'index out of bounds exception' error. I used int to create arrays before, what's the difference between int arrays and Integer arrays? Thanks in advance.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
Nik
  • 195
  • 3
  • 5
  • 12

1 Answers1

7

Arrays.asList(T...) takes varargs. When you pass Integer[], type T is inferred as Integer, each element of the Integer[] is unpacked as different argument of varargs.

However, when you pass an int[], since int is not an object, T is inferred as int[]. So, what is passed to the method is a single element array, with value int[]. So, the number of varargs is different in both the cases. Hence, accessing index 1 will give you error, when you pass int[].

So, in one line - Integer[] is an array of references to objects, whereas, int[] is itself an object.

You can do a simple test, with this method:

public static <T> void test(T... args) {
    System.out.println(args.length);
}

Then call this method as:

int[] arr = {1, 2, 3};
Integer[] arr2 = {1, 2, 3};

test(arr);   // passing `int[]`. length is 1
test(arr2);  // passing `Integer[]`. length is 3
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525