記渣渣踩坑系列 -使用Arrays.asList 將陣列array 轉為List 踩坑記錄
阿新 • • 發佈:2019-02-06
/** * zhazhahao使用 Arrays.asList:將陣列轉為List集合引發的思考。 * * 問題1、Arrays.asList 方法傳入基本型別陣列(int[])和包裝型別陣列(Integer[]) * 返回資料格式是否都為List<int>或List<Integer>? * * 問題2、返回的集合List 是否是傳統意義上的集合:是否做add和remove刪除動作 * * TestZhaZhaAsList * @author shiyuqiong * @date 2018年9月19日 上午10:40:44 * */ public class TestZhaZhaAsList { public static void main(String[] args) { int[] intList={1,2};// eg1: System.out.println(JSONObject.toJSONString(Arrays.asList(intList)));// eg2:輸出 [[1,2]] Integer[] integerList={1,2};// eg3: System.out.println(JSONObject.toJSONString(Arrays.asList(integerList)));// eg4:輸出 [1,2] testIn(intList);//5 輸出什麼? testIn(integerList);//6 輸出什麼? } public static <T> void testIn(T...args){ System.out.println(JSONObject.toJSONString(args)); } } /** * 答一:在執行程式碼時候回發現 標註為2的程式碼行輸出結構為 [[1,2]], * 程式碼4:位置輸出為 [1,2],那麼為什麼int[]基本型別陣列轉為List會輸出 * 結果為一個二維陣列? * 看Arrays.asList(T... a) ,發現asList方法引數為 “泛型可變引數型別”, * 經編譯器編譯進行型別擦除後變為: Arrays.asList(Object[] a)。 * 然而,int[] 不能被轉為 Object[]陣列型別。 * 因為 auto boxing 和 unboxing 是針對 基本型別和其對應的封裝型別來講。 * 這時候eg2 這個位置, intList 引數會被當成 Object[] 對應中儲存的 * 物件:Arrays.asList(Object[] a) a 變成 int[][], * 以至於Arrays.asList返回為 List<int[]> 。 * * Integer[] 可轉為Object[] 所以此時Arrays.asList(Object[] a) * a 的實際資料型別了Integer[] 陣列型別 * * * 答二: 對於第二個問題可見文件( * * Returns a fixed-size list backed by the specified array. (Changes to * * the returned list "write through" to the array.) This method acts * * as bridge between array-based and collection-based APIs, in * * combination with {@link Collection#toArray}. The returned list is * * serializable and implements {@link RandomAccess}. * )意思是說:asList返回是一個固定長度的List 。該方法主要是將array轉為List * 可使用 collection中對應的api。 * 且這裡Arrays.asList返回ArrayList 其實是java.util.Arrays.ArrayList.ArrayList * 並不是java.util.ArrayList<E> 。 * 之所以 asList 返回的 集合能夠使用collection API。: * java.util.Arrays.ArrayList. ArrayList<E> extends AbstractList<E> * implements List<E>, RandomAccess, Cloneable, java.io.Serializable * * * */