天天看點

Arrays.asList()方法總結

1、該方法對于基本資料類型的數組支援并不好,當數組是基本資料類型時不建議使用 :

public static void test1 () {
	int[] a_int = { 1, 2, 3, 4 };  
        /* 預期輸出應該是1,2,3,4,但實際上輸出的僅僅是一個引用, 這裡它把a_int當成了一個元素 */  
        List a_int_List = Arrays.asList(a_int);  
        for (int i=0 ;i<a_int_List.size();i++ ) {
        	System.out.println(a_int_List.get(i));
        }
}
           

輸出:[[email protected]

當數組是對象類型時,可以得到我們的預期:

public static void test2 () {
		Integer[] a_int = { 1, 2, 3, 4 };  
        List a_int_List = Arrays.asList(a_int);  
        for (int i=0 ;i<a_int_List.size();i++ ) {
        	System.out.println(a_int_List.get(i));
        }
}
           

輸出:

1

2

3

4

2、當使用asList()方法時,數組就和清單連結在一起了。當更新其中之一時,另一個将自動獲得更新。 

注意:僅僅針對對象數組類型,基本資料類型數組不具備該特性

public static void test3 () {
	Integer[] a_int = { 1, 2, 3, 4 };  
        /* 預期輸出應該是1,2,3,4,但實際上輸出的僅僅是一個引用, 這裡它把a_int當成了一個元素 */  
        List<Integer> a_int_List = Arrays.asList(a_int);  
        
        a_int_List.set(0, 10);
        
        a_int[1]=0;
        
        for (int i=0 ;i<a_int_List.size();i++ ) {
        	System.out.println(a_int_List.get(i));
        }
        System.out.println();
        for (Integer i : a_int) {
        	System.out.println(i);
        }
}
           

輸出:

10

3

4

10

3

4

3、asList得到的List是Arrays内部類的List,沒有add和remove方法(方法很少)

public static void test3 () {
	Integer[] a_int = { 1, 2, 3, 4 };  
        /* 預期輸出應該是1,2,3,4,但實際上輸出的僅僅是一個引用, 這裡它把a_int當成了一個元素 */  
        List<Integer> a_int_List = Arrays.asList(a_int);  
        
        a_int_List.add(0);
        
        
        for (int i=0 ;i<a_int_List.size();i++ ) {
        	System.out.println(a_int_List.get(i));
        }
        System.out.println();
        for (Integer i : a_int) {
        	System.out.println(i);
        }
}
           

當調用a_int_List.add(0);時,會報錯。