泛型之前:
在泛型之前,其他的容器類在處理對象時,都將它們是做沒有任何具體類型。也就是說,
它們將這些對象都當做Java中所有類的根類Object處理。數組之所以優於泛型之前的容器,
就是因為你可以建立一個數組去持有某種具體類型,這意味著你可以通過編譯器檢查,防止錯誤類型和抽取不當類型。
數組可以持有基本類型,而泛型之前的容器則不能。
泛型之後:
有了泛型,容器就可以指定並檢查它們所持有對象的類型,並且有了自動封裝機制,因此,容器看起來還是能夠持有基本類型。
我們看一個Demo。
class BerylliumSphere {private static long counter;// 靜態變數是屬於類的,且唯一。private final long id = counter++;// final變數值不可以被改變public String toString() {return "Sphere " + id;}}public class Main {public static void main(String[] args) {/** *對象數組 * */BerylliumSphere[] spheres = new BerylliumSphere[10]; // 建立一個數組對象,數組內引用被初始化為NULL// [null, null, null, null, null, null, null, null, null, null]System.out.println(Arrays.toString(spheres));// 在堆中建立對象,交給數組的引用for (int i = 0; i < 5; i++) {spheres[i] = new BerylliumSphere();}// [Sphere 0, Sphere 1, Sphere 2, Sphere 3, Sphere 4, null, null, null, null, null]System.out.println(Arrays.toString(spheres));// Sphere 4System.out.println(spheres[4]);/** * 容器 * */List<BerylliumSphere> sphereList = new ArrayList<BerylliumSphere>();// []System.out.println(sphereList);for (int i = 0; i < 5; i++) {sphereList.add(new BerylliumSphere());}// [Sphere 5, Sphere 6, Sphere 7, Sphere 8, Sphere 9]System.out.println(sphereList);// Sphere 9System.out.println(sphereList.get(4));/** * 原始類型數組 * */int[] integers = {0, 1, 2, 3, 4, 5};// [0, 1, 2, 3, 4, 5]System.out.println(Arrays.toString(integers));// 4System.out.println(integers[4]);/** * 原始類型容器 * */List<Integer> intList = new ArrayList<Integer>(Arrays.asList(0,1,2,3,4,5));intList.add(97);// [0, 1, 2, 3, 4, 5, 97]System.out.println(intList);// 4System.out.println(intList.get(4));}}
結果:
隨著自動封裝機制的出現,容器已經可以與數組幾乎一樣方便的用於基本類型中了。
數組碩果僅存的有點就是效率。然而,如果要解決更一般化的問題,那數組就可能會受到過多的限制,因此這種情況下,你還是會使用容器。