首页 > 编程 > Java > 正文

Java陷阱(一)——ArrayList.asList

2019-11-08 03:10:48
字体:
来源:转载
供稿:网友

一、问题代码

    话不多说,直接上问题代码:

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));


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表