Arrays.asList(1,2,3,4,5) 返回的时Arrays中自定义的ArrayList
List<String> list = Arrays.asList("1", "2", "3");list.add("4");//调用的是抽象类中的方法System.out.println(list);
1,模拟List 接口public interface Foo {void f();}2,模拟AbstractListpublic abstract class AbstractFoo implements Foo {@Overridepublic void f() {throw new UnsupportedOperationException();}}3,模拟Arrayspublic class ArraysFoo {public static Foo asList(String ... param){return new FooImpl();}//模拟Arrays内部的ArrayListprivate static class FooImpl extends AbstractFoo{}}4,模拟外部的ArrayListpublic class FooImpl extends AbstractFoo {@Overridepublic void f() {System.out.println("模拟java.util.ArrayList");}}5,测试public class App {public static void main(String[] args) {//此时对于ArraysFoo 是拿不到自己内部定义的私有嵌套类的Foo foo = (AbstractFoo)ArraysFoo.asList("");//foo.f(); 调用的永远是抽象类中的方法((FooImpl)foo).f();//转换也是报错的System.out.println(foo);}}6,除非重新包装一下ArrayslistList<String> list = new ArrayList<>(Arrays.asList("1", "2", "3"));System.out.println(list.getClass());list.remove("1");list.add("4");System.out.println(list);
添加一组元素的完整示例
public class CollectionsAddAll {public static void main(String[] args) {//Arrays.asList(1,2,3,4,5) 将可变的参数列表转为ListCollection<Integer> collection = new ArrayList<>(Arrays.asList(1,2,3,4,5));Integer[] moreInts = {6,7,8,9,10};collection.addAll(Arrays.asList(moreInts));//System.out.println(collection);Collections.addAll(collection,11,12,13,14,15);//null 值也可以添加进来Collections.addAll(collection,null,null);//变参实质是数组,当你添加一数组,但没进行初始化的时候,会报NullPointerExceptionInteger[] arrays = null;//Collections.addAll(collection,arrays); NullPointer异常1//collection = null;//Collections.addAll(collection,1); NullPointer异常2System.out.println(collection);//boolean containsAll = collection.containsAll(Arrays.asList(1, 2, 3, 4, 5));//System.out.println(containsAll);//collection.removeAll(Arrays.asList(1, 2, 3, 4, 5));//System.out.println(collection);//交集//collection.retainAll(Arrays.asList(1, 2, 3, 4, 5));//System.out.println(collection);final Iterator<Integer> iterator = collection.iterator();while (iterator.hasNext()){System.out.println(iterator.next());iterator.remove();////collection.remove(3);//ConcurrentModificationException}System.out.println("通过迭代器移除的后数据:"+collection);}}
