当我遇到Joel Spolsky时,我正在阅读更多关于Joel on Software的文章,说明一种特定类型的程序员知道a 和Java/C#(面向对象编程语言)之间的区别.intInteger
那么区别是什么呢?
当我做以下,
arrayList1- 包含一个元素,它是一个int[].arrayList2- 不编译(错误:构造函数ArrayList<Integer>(List<int[]>)未定义)arrayList3- 包含7个元素,它们是Integer对象这是代码:
int[] intArray = new int[]{2,3,4,5,6,7,8};
ArrayList arrayList1 = new ArrayList(Arrays.asList(intArray));
ArrayList<Integer> arrayList2 = new ArrayList<Integer>(Arrays.asList(intArray));
Integer[] integerArray = new Integer[]{2,3,4,5,6,7,8};
ArrayList<Integer> arrayList3 = new ArrayList<Integer>(Arrays.asList(integerArray));
Run Code Online (Sandbox Code Playgroud)
问题:
为什么编译器不自动将int[]to 中的元素包装Integer并创建ArrayList<Integer>?这背后的原因是什么?这是我的愚蠢还是其他原因?
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));
}
}
Run Code Online (Sandbox Code Playgroud)
我知道int是一个原始类型,而Integer是一个类.但是在这个脚本中,当我尝试使用int而不是Integer时,我得到'index out of bounds exception'错误.之前我使用int来创建数组,int数组和Integer数组之间的区别是什么?提前致谢.