问题描述:
将Array转为List,通常我们会直接使用 Arrays.asList(array) 来实现。
但是如果对List继续调用List对应的方法时,神奇的事发生了,报错:java.lang.UnsupportedOperationException
源码:
List<String> list = Arrays.asList(array);
@SafeVarargs
@SuppressWarnings("varargs")
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
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) {
a = Objects.requireNonNull(array);
}
@Override
public int size() {
return a.length;
}
@Override
public Object[] toArray() {
return a.clone();
}
@Override
@SuppressWarnings("unchecked")
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;
}
@Override
public E get(int index) {
return a[index];
}
@Override
public E set(int index, E element) {
E oldValue = a[index];
a[index] = element;
return oldValue;
}
@Override
public int indexOf(Object o) {
E[] a = this.a;
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;
}
@Override
public boolean contains(Object o) {
return indexOf(o) != -1;
}
@Override
public Spliterator<E> spliterator() {
return Spliterators.spliterator(a, Spliterator.ORDERED);
}
@Override
public void forEach(Consumer<? super E> action) {
Objects.requireNonNull(action);
for (E e : a) {
action.accept(e);
}
}
@Override
public void replaceAll(UnaryOperator<E> operator) {
Objects.requireNonNull(operator);
E[] a = this.a;
for (int i = 0; i < a.length; i++) {
a[i] = operator.apply(a[i]);
}
}
@Override
public void sort(Comparator<? super E> c) {
Arrays.sort(a, c);
}
}
...
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E>
小结:
Arrays.asList(array)转List虽然方便,但是实现的方法有限,有些方法未实现时,调用会报错:java.lang.UnsupportedOperationException。
解决方法:
* List<String> lists = Arrays.asList(array);
* List<String> list=new ArrayList<>(lists);--将List转为java.util.ArrayList即可使用接口。
* @param args
*/
public static void main(String[] args) {
String[] array={"1","2","3"};
List<String> lists = Arrays.asList(array);
List<String> list=new ArrayList<>(lists);
List<String> list1 = new ArrayList<>();
list1.add("4");
list.addAll(list1);
}
|