Array與List的簡單應用

一、數組的定義

		int[] array1 = new int[10];
		
		int array2[] = new int[10];//這兩種方式一樣
		
		int[] array3 = {1,2,3,4};
		
		int[] array4 = new int[]{1,2,3,4};

二、數組的複製

數組的複製用到:System.arraycopy,從指定源數組中複製一個數組,複製從指定的位置開始,到目標數組的指定位置結束

Arrays.copyOf,從指定數據複製一個數組,複製指定長度(int[] original, int newLength)

 int[] arr1 = { 1, 2, 3, 4, 5 };
        int[] arr2 = new int[6];
        //從arr1中下標爲1開始複製數據,而arr2從下標爲0開始賦值,
        System.arraycopy(arr1, 1, arr2, 0, 2);
        /*[2, 3, 0, 0, 0, 0]*/
        System.out.println(Arrays.toString(arr2));
         
        
        int[] arr11 = { 1, 2, 3, 4, 5 };
        int[] arr22 = new int[6];
        /*[0, 1, 2, 3, 0, 0]*/
      //從arr11中下標爲0開始複製數據,而arr22從下標爲1開始賦值,
        System.arraycopy(arr11, 0, arr22, 1, 3);
        System.out.println(Arrays.toString(arr22));

        /*[1, 2, 3, 4, 5]*/
        int a[]= Arrays.copyOf(arr1, arr1.length);

三 、集合與數組的相互轉換

      a)數組轉集合

           List l=(List) Arrays.asList(a);

     b)集合轉數組

       ArrayList list=new ArrayList();
       list.add("1");
       list.add("2");
       Object[] obj=list.toArray();
       System.out.println(Arrays.toString(obj));//[1, 2]



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