在JDK 1.7中,有一个ArrayList声明被使用asList.
为什么他们做了一个新的private static class而不是使用java.util.ArrayList:
@SafeVarargs
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
/**
* @serial include
*/
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];
}
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;
}
}
Run Code Online (Sandbox Code Playgroud)
Rus*_*ser 25
因为List返回的Arrays.asList()是由给定的数组支持的.它包裹了那个数组; 对数组的更改反映在数组中List,反之亦然.
另外,由于这个原因,List这里返回的具有固定的大小.所以,它不能是ArrayList因为ArrayList可以增长或缩小.
| 归档时间: |
|
| 查看次数: |
719 次 |
| 最近记录: |