16.数组

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>();

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章