為什麼Java裡的Arrays.asList不能用add和remove方法?

來源:互聯網
上載者:User

標籤:read   ted   code   通過   rac   private   method   exec   row   

在平時的開發過程中,我們知道能夠將一個Array的對象轉化為List。這種操作,我們僅僅要採用Arrays.asList這種方法即可了。筆者前段時間一直用這種方法,有一天,我發現通過Arrays.asList得到的List無法進行add和remove等操作。


以下是一段非常easy的測試代碼:  

    public class MainFacade {        public static void main(String[] args) {            List<Integer> list = Arrays.asList(1,2,3);            list.add(5);            System.out.print(list.toString());        }    }

只是上面的代碼會throw出一個UnsupportedOperationException這種異常  

Exception in thread "main" java.lang.UnsupportedOperationException at java.util.AbstractList.add(AbstractList.java:148) at java.util.AbstractList.add(AbstractList.java:108) at org.popkit.MainFacade.main(MainFacade.java:14) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

終其原因是Arrays.asList方法返回的ArrayList是繼承自AbstractList同一時候實現
了RandomAccess和Serializable介面。定義例如以下:  

    private static class ArrayList<E> extends AbstractList<E>        implements RandomAccess, java.io.Serializable

我們再來看看AbstractList這個類的定義:  

    public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> 

這時我們發現AbstractList這個類的set add remove方法定義例如以下:

    public void add(int index, E element) {        throw new UnsupportedOperationException();    }    public E set(int index, E element) {        throw new UnsupportedOperationException();    }    public E remove(int index) {        throw new UnsupportedOperationException();    }
如今知道了它throw UnsupportedOperationException異常的原因了。

 

通過上面的分析,我們知道。事實上通過asList方法得到的List是僅僅讀的。那麼平時我們如何避免這種發生錯誤?我們能夠採用例如以下方法:  

    List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3));






為什麼Java裡的Arrays.asList不能用add和remove方法?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.