Java – what is the difference between int and integer in this script?

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

public class arraysAsList {


    public static void main(String[] args) {

        String [] arrayA = {"@R_471_2419@","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 know that 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 the error 'index out of bounds exception' I used int to create arrays before. What is the difference between int arrays and integer arrays? Thank you in advance

Solution

Arrays. asList(T...) Varargs. Is required When you pass integer [], type T is inferred as integer, and each element of integer [] is decompressed into different parameters of varargs

However, when you pass int [], because int is not an object, t is inferred as int [] Therefore, the method is passed a single element array with the value int [] Therefore, the number of varargs is different in both cases Therefore, accessing index 1 will give an error

Therefore, in one line - integer [] is a reference array of objects, and int [] itself is an object

You can use this method for simple tests:

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

This method is then called:

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

test(arr);   // passing `int[]`. length is 1
test(arr2);  // passing `Integer[]`. length is 3
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>