Java陷阱(一)——ArrayList.asList
生活随笔
收集整理的這篇文章主要介紹了
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.UnsupportedOperationExceptionat 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));
總結
以上是生活随笔為你收集整理的Java陷阱(一)——ArrayList.asList的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Mysql:Sql的执行顺序
- 下一篇: 评审会上产品经理常被怼的话