因爲之前面試過程中,經常在基礎問題上出現遺漏,於是有了一個想法,每天看一些簡單的java源碼,由易到難。在此做一個記錄,如果有感興趣的小夥伴可以一起學習,遇到問題的小夥伴也可以查閱作爲一個借鑑。
關於Arrays.asList(String[] arr)問題:
今天來看看Arrays.asList(String arr)中的問題。在日程編程中,我們有可能會用到Arrays.asList(String arr)將一個數組轉爲一個List的操作,那麼這些操作我們應該注意些什麼呢?
首先來看我的代碼和錯誤:
Code:
/**
* @Author : xiefei
* @Date : 2019/12/13 9:28
* @Description :
**/
public class Demo {
public static void main(String[] args) {
String[] arr = {"丁甲","Calvin","weibo"};
List<String> list = Arrays.asList(arr);
String str = "zhanghao";
list.add(str);
for (String strr : list) {
System.out.println(strr);
}
}
}
Error:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at com.xf.eureka_erver.Demo.main(Demo.java:16)
那麼爲什麼會出現這種UnsupportedOperationException的錯誤呢?我們來一起看看源碼:
點開asList方法:
@SafeVarargs
@SuppressWarnings("varargs")
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
我們看見這裏返回的是一個新的ArrayList<>(a);那麼這個arrayList和我們平時用的java.util.ArrayList有什麼區別呢?我們接着點進去看:
/**
* @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) {
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);
}
}
我們可看到這裏的ArrayList是Arrays的一個靜態內部類,同時他也是繼承了AbstractList<E>的,但是爲什麼他使用add方法向其中添加元素的時候就會報UnsupportedOperationException錯呢?我們接着往下看,發現這個ArrayList的實現內裏面沒有重寫add()方法和remove()方法。
我在再來看java.util.ArrayList的源碼:
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
......
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
......
/**
* Removes the element at the specified position in this list.
* Shifts any subsequent elements to the left (subtracts one from their
* indices).
*
* @param index the index of the element to be removed
* @return the element that was removed from the list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
}
同樣也是繼承了AbstractList<E>的,但是java.util.ArrayList下的重寫了更多的方法,其中就包括add()、remove()方法,因此它就能夠執行add、remove方法。
如果我們想要對由String[] arr轉換的數組進行添加刪除操作就需要將其重新寫入一個util包下的ArrayList,然後再操作就行啦!