1.數組和其他容器的區別
效率,類型和保存基本類型的能力。
效率是以數組大小被固定的代價換來的。
在泛型之前,容器的對象都被當做object,而數組則可以限制某種類型。
其他容器通過包裝基本類型來保存。
2.對象和基本類型數組
對象數組保存引用。
基本類型數組保存值。
3.粗糙數組
維度長度不一數組。
int[][][] a = new int[rand.nextInt(7)][][];
for(int i = 0; i < a.length; i++) {
a[i] = new int[rand.nextInt(5)][];
for(int j = 0; j < a[i].length; j++)
a[i][j] = new int[rand.nextInt(5)];
}
4.java.util.Arrays
其中的deepToString可以對數組值做深層輸出。
int[] a = new int[5];
Arrays.fill(a,5);
String[] b = new String[9];
Arrays.fill(b,"hello");
Arrays.fill(b,3,5,"world");//填充數組的3到5的區域。
int[] arr = {93, 5, 3, 55, 57, 7, 2 ,73, 41, 91};
Arrays.sort(arr);//排序
Arrays.binarySearch(arr, key);//如果沒找到返回負值。返回值=插入點-1;
Arrays.equals(arr1, arr2)); //比較兩個數組,返回true或false
Arrays.deepEquals(arr1, arr2));//可以對二維仍至三維以上的數組進行比較是否相等
System.arraycopy(源數組,源起始位置,目標數組,目標起始位置,複製個數)如果是對象則複製 引用。
5.數組和泛型
兩者不能很好的結合。
Peel<Banana>[] peels = new Peel<Banana>[10];//illegal
擦除會移除參數類型信息,而數組必須知道它們所持有的確切類型,以強制保證類型安全。
但是可以創建泛型數組引用。
List<String>[] ls;
然後創建非泛型數組,將其強制轉換。
List[] la = new List[10];
ls = (List<String>[])la;
ls[1] = new ArrayList<String>;
// Compile-time checking produces an error:
//! ls[1] = new ArrayList<Integer>();
因爲數組是協變類型的,List<String> 也是一個Object[].
Object[] objects = ls; // So assignment is OK
// Compiles and runs without complaint:
objects[1] = new ArrayList<Integer>();