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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值