Java陷阱(一)——ArrayList.asList,
分享于 点击 25848 次 点评:165
Java陷阱(一)——ArrayList.asList,
一、问题代码
话不多说,直接上问题代码:
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));
相关文章
- 暂无相关文章
用户点评