【问题标题】:What is the difference between int and Integer in this script?这个脚本中的 int 和 Integer 有什么区别?
【发布时间】:2013-10-20 10:19:56
【问题描述】:
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));

    }

}

我意识到 int 是一个原始类型,而 Integer 是一个类。但是在这个脚本中,当我尝试使用 int 而不是 Integer 时,我得到“索引超出范围异常”错误。 我之前用int创建数组,int数组和Integer数组有什么区别?提前致谢。

【问题讨论】:

    标签: java arrays list integer int


    【解决方案1】:

    Arrays.asList(T...) 采用可变参数。当您传递Integer[] 时,类型T 被推断为Integer,Integer[] 的每个元素都被解包为可变参数的不同参数。

    但是,当您传递int[] 时,由于int 不是对象,T 被推断为int[]。因此,传递给该方法的是一个单元素数组,其值为int[]。因此,两种情况下可变参数的数量是不同的。因此,当您通过int[] 时,访问索引1 会报错。

    因此,在一行中 - Integer[] 是一个对象引用数组,而 int[] 本身就是一个对象。

    你可以用这个方法做一个简单的测试:

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

    然后调用这个方法为:

    int[] arr = {1, 2, 3};
    Integer[] arr2 = {1, 2, 3};
    
    test(arr);   // passing `int[]`. length is 1
    test(arr2);  // passing `Integer[]`. length is 3
    

    【讨论】:

      猜你喜欢
      • 2011-03-26
      • 2010-11-19
      • 2015-01-29
      • 2013-09-21
      • 2010-10-15
      • 2010-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多