通常很多人為了操作方便喜歡把數(shù)組轉(zhuǎn)換成集合再操作,jdk也剛好有這樣的方法,Arrays.asList ,我們看看他的內(nèi)部實(shí)現(xiàn)
/** * 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}. * * <p>This method also provides a convenient way to create a fixed-size * list initialized to contain several elements: * <pre> * List<String> stooges = Arrays.asList('Larry', 'Moe', 'Curly'); * </pre> * * @param <T> the class of the objects in the array * @param a the array by which the list will be backed * @return a list view of the specified array */ @SafeVarargs @SuppressWarnings('varargs') public static <T> List<T> asList(T... a) { return new ArrayList<>(a); }
我們通過方法上面的描述可以得知,通過這樣調(diào)用將數(shù)組轉(zhuǎn)換成集合,返回的集合大小是固定的,因此往里面再添加元素肯定報(bào)錯(cuò)了。 那么解決這個(gè)問題的正確姿勢(shì)是什么,稍微修改下即可: //錯(cuò)誤姿勢(shì) List<String> list1 = Arrays.asList('1', '2', '3'); List<String> list2 = Arrays.asList('4', '5', '6'); list1.addAll(list2);
//正確姿勢(shì) List<String> list3 = new ArrayList<>(Arrays.asList('1', '2', '3')); List<String> list4 = new ArrayList<>(Arrays.asList('1', '2', '3')); list3.addAll(list4);
順便回顧下數(shù)組與集合的一些區(qū)別:
|