Quote:
Alibaba said Java development specification to use tools Arrays. The asList () method to convert the array collection, cannot use the modify the related methods of collection, its the add/remove/clear method will throw an UnsupportedOperationException (), let’s take a look at Here’s why this happens.
Problem analysis:
Let’s do a test
public static void main(String[] args) {
List<String> list = Arrays.asList("a"."b"."c");
// list.clear();
// list.remove("a");
// list.add("g");
}
Copy the code
The annotated three lines can be uncommented separately, and the run does produce the exception described in the specification. Let’s take a look at what arrays.aslist () does.
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
Copy the code
It looks like a normal method, but in fact when you click on an ArrayList, it turns out that an ArrayList is not an ArrayList.
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(a) {
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;
}
//
Copy the code
It’s an inner class of Arrays. And this inner class doesn’t have add,clear, and remove methods, so the exception actually comes from AbstractList.
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
public E remove(int index) {
throw new UnsupportedOperationException();
}
Copy the code
Click on it to see where the exception was thrown, and the bottom layer of clear will also call remove so it will throw an exception.
Conclusion:
1.Arrays. AsList () 2. If arrays.aslist () is used, it’s best not to use its collections; 3. List List = new ArrayList<>(array.asList (“a”, “b”, “c”))