关于Arrays.asList()方法的使用
作者:互联网
Arrays.asList
创建的 ArrayList
的使用
Arrays.asList()
方法生成的 ArrayList
类对象,在调用 add(),remove()
等方法时会报错
public static void main(String[] args) {
List<String> list = Arrays.asList("Java", "C++", "Python");
list.add("C#");
}
- 通过源码分析
Arrays.asList()
生成的ArrayList
对象不是我们所讲的java.util.ArrayList
Arrays
中的内部类ArrayList
虽然继承了AbstractList
类,但是它没有重写AbstractList
类的add(),remove()
等方法
public class 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) {
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);
}
}
}
- 所以使用
Arrays
中的内部类ArrayList
直接调用这些方法时会调用它父类AbstractList
的同名方法,而AbstractList
类中这些方法是没有具体的实现操作的,而是简单地抛出了异常
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
public boolean add(E e) {
// 调用下面的 add()
add(size(), e);
return true;
}
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
public E remove(int index) {
throw new UnsupportedOperationException();
}
}
标签:return,Arrays,int,关于,Override,public,asList,size 来源: https://blog.csdn.net/weixin_38192427/article/details/122509294