简体   繁体   English

这个脚本中int和Integer有什么区别?

[英]What is the difference between int and Integer in this script?

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. 我知道int是一个原始类型,而Integer是一个类。 But in this script, when i try to use int instead of Integer, i get 'index out of bounds exception' error. 但是在这个脚本中,当我尝试使用int而不是Integer时,我得到'index out of bounds exception'错误。 I used int to create arrays before, what's the difference between int arrays and Integer arrays? 之前我使用int来创建数组,int数组和Integer数组之间的区别是什么? Thanks in advance. 提前致谢。

Arrays.asList(T...) takes varargs. Arrays.asList(T...)需要varargs。 When you pass Integer[] , type T is inferred as Integer , each element of the Integer[] is unpacked as different argument of varargs. 当你传递Integer[] ,类型T被推断为IntegerInteger[]每个元素都被解压缩为varargs的不同参数。

However, when you pass an int[] , since int is not an object, T is inferred as int[] . 但是,当您传递int[] ,因为int不是对象,所以T被推断为int[] So, what is passed to the method is a single element array, with value int[] . 因此,传递给该方法的是单个元素数组,其值为int[] So, the number of varargs is different in both the cases. 因此,两种情况下的varargs数量都不同。 Hence, accessing index 1 will give you error, when you pass int[] . 因此,当您传递int[]时,访问索引1将给出错误。

So, in one line - Integer[] is an array of references to objects, whereas, int[] is itself an object. 因此,在一行中 - Integer[]是对象的引用数组,而int[]本身就是一个对象。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM