》 Arrays.asList(T … a)方法的使用
》UnsupportedOperationException分析
-
Arrays.asList(T … a)方法的使用
package cn.itcast.day24.varparam; import java.util.Arrays; import java.util.List; /** * * public static <T> List<T> asList(T... a):把数组转为集合 * * 注意: * 转成的集合本质还是数组,长度是固定的,所以转换完成得到的集合,不能增删(会改变数组长度),只能修改。 * */ public class AsListDemo { public static void main(String[] args) { //定义一个数组 // String[] arrStr={"林青霞","武松","猪八戒"}; // List<String> list=Arrays.asList(arrStr); List<String> list=Arrays.asList("java","world","hello"); //UnsupportedOperationException list.add("javaee");//错误 // list.remove(1);//错误 list.set(1, "javaee");//修改成功 // for(String s:list){ // System.out.println(s); // } } }
-
UnsupportedOperationException分析
可以看到Arrays的私有内部类Arrays$ArrayList中,没有实现来自父类AbstractList的add(),remove()等长度相关的方法,
所以抛出 UnsupportedOperationException,意思是:不支持请求的操作(当然不支持)
private static class ArrayList<E> extends AbstractList<E> implements RandomAccess, java.io.Serializable { private static final long serialVersionUID = -2764017481108945198L; private final E[] a; ArrayList(E[] array) { if (array==null) throw new NullPointerException(); a = array; } public int size() { return a.length; } public Object[] toArray() { return a.clone(); } public <T> T[] toArray(T[] a) { int size = size(); if (a.length < size) return Arrays.copyOf(this.a, size, (Class<? extends T[]>) a.getClass()); System.arraycopy(this.a, 0, a, 0, size); if (a.length > size) a[size] = null; return a; } public E get(int index) { return a[index]; } //重写了父类AbstractList的set方法,所以set时没有抛出异常.而add和remove方法来自基类,所以都抛出了异常。public E set(int index, E element) { E oldValue = a[index]; a[index] = element; return oldValue; } public int indexOf(Object o) { if (o==null) { for (int i=0; i<a.length; i++) if (a[i]==null) return i; } else { for (int i=0; i<a.length; i++) if (o.equals(a[i])) return i; } return -1; } public boolean contains(Object o) { return indexOf(o) != -1; } }
AbstractList源码:
package java.util; public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> { public E set(int index, E element) { throw new UnsupportedOperationException(); } public boolean add(E e) { add(size(), e); return true; } public void add(int index, E element) { throw new UnsupportedOperationException(); } public E remove(int index) { throw new UnsupportedOperationException(); } public void clear() { removeRange(0, size()); } public E set(int index, E element) { throw new UnsupportedOperationException(); } abstract public E get(int index); }
时间: 2024-10-13 05:06:50