数组与其他容器的区别: 效率、类型 、保存基本类型的能力。
数组特点:是一种效率最高的存储和随机访问的方法。
数组的缺点:大小固定,同时在生命周期中是不可变的。
数组的扩容:
虽然数组的大小虽然不可变,当时我们可以用一下特殊的手段对数组进行扩容。就像Arraylist一样,底层虽然是数组,当在超过10个默认容量后就会对进行扩容。
package com.package16;public class Example01 {public static void main(String[] args) {int [] numbers=new int[2];System.out.println("扩容前:"+numbers.length);int [] numbers2=new int[5];numbers=numbers2;System.out.println("扩容后:"+numbers.length);}}
数组与(泛型)容器比较:
数组可以储存基本类型,但在泛型出现前的容器却不行。当有了泛型后,容器可以指定并检查所持有的类型,并且有了自动包装机制。
package com.package16;import java.util.ArrayList;import java.util.Arrays;class BerylliumSphere{private static long count=0;private final long id=count++;@Overridepublic String toString() {return "BerylliumSphere" + id;}}public class Contents {public static void main(String[] args) {BerylliumSphere[] bery = new BerylliumSphere[10];for (int i=0;i<5;i++){bery[i]=new BerylliumSphere();}System.out.println(Arrays.toString(bery));System.out.println(bery[4]);ArrayList<Integer> integers = new ArrayList<>(Arrays.asList(1,2,3,4,5));System.out.println(integers);System.out.println(integers.get(4));}}Output:[BerylliumSphere0, BerylliumSphere1, BerylliumSphere2, BerylliumSphere3, BerylliumSphere4, null, null, null, null, null]BerylliumSphere4[1, 2, 3, 4, 5]5
