Java陷阱(一)——ArrayList.asList
阿新 • • 發佈:2019-02-08
一、問題程式碼
話不多說,直接上問題程式碼:
package com.pajk.recsys.dk.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.pajk.recsys.utils.CommonUtils;
public class CommonTest {
public static List<String> UnsupportedOperationExceptionTest(List<String> source){
source.add ("12312");
return source;
}
public static void main(String args[]){
String str = "123,456,7899";
String[] items = str.trim().split(",");
List<String> realAdd = Arrays.asList(items);
realAdd.add("123123123");
List<String> xxx = UnsupportedOperationExceptionTest(realAdd);
System.out.println(xxx);
}
}
上述程式碼丟擲異常:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(Unknown Source)
at java.util.AbstractList.add(Unknown Source)
at com.pajk.recsys.dk.test.CommonTest.main(CommonTest.java:20)
問題出在Arrays.asList(items)。
二、Arrays.asList() 原始碼
private static final class ArrayList<E> extends AbstractList<E>
implements Serializable, RandomAccess
{
// We override the necessary methods, plus others which will be much
// more efficient with direct iteration rather than relying on iterator().
/**
* Compatible with JDK 1.4.
*/
private static final long serialVersionUID = -2764017481108945198L;
/**
* The array we are viewing.
* @serial the array
*/
private final E[] a;
/**
* Construct a list view of the array.
* @param a the array to view
* @throws NullPointerException if a is null
*/
ArrayList(E[] a)
{
// We have to explicitly check.
if (a == null)
throw new NullPointerException();
this.a = a;
}
....
public static <T> List<T> asList(final T... a)
{
return new Arrays.ArrayList(a);
}
由上邊程式碼可知, asList返回一個final的,固定長度的ArrayList類,並不是java.util.ArrayList, 所以直接利用它無法執行改變list長度的操作, 比如 add、remove等。
三、修改方法
List<String> realAdd = new ArrayList(Arrays.asList(items));