记得以前写过一段这样的代码:
String[] arr={"a","b","c"};
List l = Arrays.asList(arr);
l.add("d");
List l = Arrays.asList(arr);
l.add("d");
自以为没有错误,结果运行下来就让系统crash掉了,后来仔细的看了下源代码,发现asList不是我想象的那么简单,1.4.2中的asList代码如下:
public static List asList(Object[] a) {
return new ArrayList(a);
}
/**
* @serial include
*/
private static class ArrayList extends AbstractList
implements RandomAccess, java.io.Serializable
{
private static final long serialVersionUID = -2764017481108945198L;
private Object[] a;
ArrayList(Object[] array) {
if (array==null)
throw new NullPointerException();
a = array;
}
public int size() {
return a.length;
}
public Object[] toArray() {
return (Object[]) a.clone();
}
public Object get(int index) {
return a[index];
}
public Object set(int index, Object element) {
Object 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;
}
}
return new ArrayList(a);
}
/**
* @serial include
*/
private static class ArrayList extends AbstractList
implements RandomAccess, java.io.Serializable
{
private static final long serialVersionUID = -2764017481108945198L;
private Object[] a;
ArrayList(Object[] array) {
if (array==null)
throw new NullPointerException();
a = array;
}
public int size() {
return a.length;
}
public Object[] toArray() {
return (Object[]) a.clone();
}
public Object get(int index) {
return a[index];
}
public Object set(int index, Object element) {
Object 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;
}
}
这个ArrayList是Arrays的内部类,可不要看成是java.util.ArrayList,从方法来看只是一个只读的数组,并没有扩展add等添加的方法,那么我刚才调用的add实际上是AbstractList中的add方法,代码一目了然了
public void add(int index, Object element) {
throw new UnsupportedOperationException();
}
throw new UnsupportedOperationException();
}
所以只能新建一个list来保存asList的返回结果,如果想做插入的话。