List<String> list = Arrays.asList("one", "two", "three"); list.add("five");
运行项目却在 list.add("five"); 处报错:
1 2 3 4
Exception in thread "main" java.lang.UnsupportedOperationException at java.util.AbstractList.add(AbstractList.java:148) at java.util.AbstractList.add(AbstractList.java:108) ...
/** * 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") publicstatic <T> List<T> asList(T... a) { returnnewArrayList<>(a); }
ArrayList(E[] array) { a = Objects.requireNonNull(array); }
@Override publicintsize() { return a.length; }
@Override public Object[] toArray() { return a.clone(); }
@Override @SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { intsize= size(); if (a.length < size) return Arrays.copyOf(this.a, size, (Class<? extendsT[]>) a.getClass()); System.arraycopy(this.a, 0, a, 0, size); if (a.length > size) a[size] = null; return a; }
@Override public E get(int index) { return a[index]; }
@Override public E set(int index, E element) { EoldValue= a[index]; a[index] = element; return oldValue; }
@Override publicintindexOf(Object o) { E[] a = this.a; if (o == null) { for (inti=0; i < a.length; i++) if (a[i] == null) return i; } else { for (inti=0; i < a.length; i++) if (o.equals(a[i])) return i; } return -1; }