平时会使用asList()方法做[数组->List]的一些转换.
但在使用时会有几个坑:
基础数据类型的数组进行转换时需要传入成封装类型的数组
再一个是的转换后的list无法进行add,remove等操作
具体原因先上源码
- asList()方法
@SafeVarargs
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
- 注意这里的ArrayList不是java.util.ArrayList,而是java.util.Arrays下的一个内部类
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;
}
1.可以看到asList方法使用了可变长参数,所以在使用基础数据类型数组时编译器会把该数组当成一个参数,即最后返回了一个List<基础类型[]> 的数据
2.由于arrayList内部类没有自己实现相关add等方法,直接继承了AbstractList的相关方法,所以会抛异常
- AbstractList的add(E e)及add(int index, E element)方法源码
public boolean add(E e) {
add(size(), e);
return true;
}
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
本文深入探讨了Java中asList方法的使用技巧与注意事项,揭示了基础数据类型转换为List时的常见陷阱及其解决办法,并解释了为何转换后的List无法进行add或remove操作。

1777

被折叠的 条评论
为什么被折叠?



