免费视频淫片aa毛片_日韩高清在线亚洲专区vr_日韩大片免费观看视频播放_亚洲欧美国产精品完整版

打開APP
userphoto
未登錄

開通VIP,暢享免費(fèi)電子書等14項(xiàng)超值服

開通VIP
java中的Arrays.asList()底層原理分析
Arrays工具類提供了一些比較實(shí)用的方法,比如sort, binarySearch, fill等。其中還有一個asList方法,此方法能夠?qū)⒁粋€變長參數(shù)或者數(shù)組轉(zhuǎn)換成List。
但是,這個生成的List,它是固定長度的,如果對其進(jìn)行add或者remove的操作,會拋出UnsupportedOperationException,為什么會這樣呢?

帶著疑問,查看一下Arrays的源碼,可以得到問題的結(jié)果。

  1. /** 
  2.     * Returns a fixed-size list backed by the specified array.  (Changes to 
  3.     * the returned list 'write through' to the array.)  This method acts 
  4.     * as bridge between array-based and collection-based APIs, in 
  5.     * combination with Collection.toArray.  The returned list is 
  6.     * serializable and implements {@link RandomAccess}. 
  7.     * 
  8.     * 

    This method also provides a convenient way to create a fixed-size 

  9.     * list initialized to contain several elements: 
  10.     * 
     
  11.     *     List stooges = Arrays.asList('Larry', 'Moe', 'Curly'); 
  12.     *  
  13.     * 
  14.     * @param a the array by which the list will be backed. 
  15.     * @return a list view of the specified array. 
  16.     * @see Collection#toArray() 
  17.     */  
  18.    public static  List asList(T... a) {  
  19. return new ArrayList(a);  


方法asList返回的是new ArrayList(a)。但是,這個ArrayList并不是java.util.ArrayList,它是一個Arrays類中的重新定義的內(nèi)部類。

具體的實(shí)現(xiàn)如下:

  1. /** 
  2.      * @serial include 
  3.      */  
  4.     private static class ArrayList extends AbstractList  
  5.     implements RandomAccess, java.io.Serializable  
  6.     {  
  7.         private static final long serialVersionUID = -2764017481108945198L;  
  8.     private Object[] a;  
  9.     ArrayList(E[] array) {  
  10.             if (array==null)  
  11.                 throw new NullPointerException();  
  12.         a = array;  
  13.     }  
  14.     public int size() {  
  15.         return a.length;  
  16.     }  
  17.     public Object[] toArray() {  
  18.         return (Object[])a.clone();  
  19.     }  
  20.     public E get(int index) {  
  21.         return (E)a[index];  
  22.     }  
  23.     public E set(int index, E element) {  
  24.         Object oldValue = a[index];  
  25.         a[index] = element;  
  26.         return (E)oldValue;  
  27.     }  
  28.         public int indexOf(Object o) {  
  29.             if (o==null) {  
  30.                 for (int i=0; i<>
  31.                     if (a[i]==null)  
  32.                         return i;  
  33.             } else {  
  34.                 for (int i=0; i<>
  35.                     if (o.equals(a[i]))  
  36.                         return i;  
  37.             }  
  38.             return -1;  
  39.         }  
  40.         public boolean contains(Object o) {  
  41.             return indexOf(o) != -1;  
  42.         }  
  43.     }  


從這個內(nèi)部類ArrayList的實(shí)現(xiàn)可以看出,它繼承了類AbstractList,但是沒有重寫add和remove方法,沒有給出具體的實(shí)現(xiàn)。查看一下AbstractList類中對add和remove方法的定義,如果一個list不支持add和remove就會拋出UnsupportedOperationException。

  1. public abstract class AbstractList extends AbstractCollection implements List {  
  2.     /** 
  3.      * Sole constructor.  (For invocation by subclass constructors, typically 
  4.      * implicit.) 
  5.      */  
  6.     protected AbstractList() {  
  7. }  
  8. /** 
  9.      * Appends the specified element to the end of this List (optional 
  10.      * operation). 

     

  11.      * 
  12.      * This implementation calls add(size(), o).

     

  13.      * 
  14.      * Note that this implementation throws an 
  15.      * UnsupportedOperationException unless add(int, Object) 
  16.      * is overridden. 
  17.      * 
  18.      * @param o element to be appended to this list. 
  19.      *  
  20.      * @return true (as per the general contract of 
  21.      * Collection.add). 
  22.      *  
  23.      * @throws UnsupportedOperationException if the add method is not 
  24.      *        supported by this Set. 
  25.      *  
  26.      * @throws ClassCastException if the class of the specified element 
  27.      *        prevents it from being added to this set. 
  28.      *  
  29.      * @throws IllegalArgumentException some aspect of this element prevents 
  30.      *            it from being added to this collection. 
  31.      */  
  32.     public boolean add(E o) {  
  33.     add(size(), o);  
  34.     return true;  
  35.     }  
  36.     /** 
  37.      * Inserts the specified element at the specified position in this list 
  38.      * (optional operation).  Shifts the element currently at that position 
  39.      * (if any) and any subsequent elements to the right (adds one to their 
  40.      * indices).

     

  41.      * 
  42.      * This implementation always throws an UnsupportedOperationException. 
  43.      * 
  44.      * @param index index at which the specified element is to be inserted. 
  45.      * @param element element to be inserted. 
  46.      *  
  47.      * @throws UnsupportedOperationException if the add method is not 
  48.      *        supported by this list. 
  49.      * @throws ClassCastException if the class of the specified element 
  50.      *        prevents it from being added to this list. 
  51.      * @throws IllegalArgumentException if some aspect of the specified 
  52.      *        element prevents it from being added to this list. 
  53.      * @throws IndexOutOfBoundsException index is out of range (index  
  54.      *        0 || index > size()). 
  55.      */  
  56.     public void add(int index, E element) {  
  57.     throw new UnsupportedOperationException();  
  58.     }  
  59.     /** 
  60.      * Removes the element at the specified position in this list (optional 
  61.      * operation).  Shifts any subsequent elements to the left (subtracts one 
  62.      * from their indices).  Returns the element that was removed from the 
  63.      * list.

     

  64.      * 
  65.      * This implementation always throws an 
  66.      * UnsupportedOperationException. 
  67.      * 
  68.      * @param index the index of the element to remove. 
  69.      * @return the element previously at the specified position. 
  70.      *  
  71.      * @throws UnsupportedOperationException if the remove method is 
  72.      *        not supported by this list. 
  73.      * @throws IndexOutOfBoundsException if the specified index is out of 
  74.      *        range (index < 0 || index >= size()). 
  75.      */  
  76.     public E remove(int index) {  
  77.     throw new UnsupportedOperationException();  
  78.     }  
  79. }  


至此,為什么Arrays.asList產(chǎn)生的List是不可添加或者刪除,否則會產(chǎn)生UnsupportedOperationException,就可以得到解釋了。


同時我們可以用List來接受Arrays.asList(array)返回的參數(shù)、原因是Arrays.asList(array)返回的雖然不是java.util.ArrayList但是返回的ArrayList同理也繼承自AbstractList

我們的AbstractList實(shí)現(xiàn)自List接口、所以可以用list接口來引用Arrays.asList(array);


如果我們想把一個變長或者數(shù)據(jù)轉(zhuǎn)變成List, 而且期望這個List能夠進(jìn)行add或者remove操作,那該怎么做呢?

我們可以寫一個類似的方法,里面直接采用java.util.ArrayList即可。

比如:
  1. import java.util.ArrayList;  
  2. import java.util.Collections;  
  3. import java.util.List;  
  4. public class MyArrays {  
  5.     public static  List asList(T... a) {  
  6.         List list = new ArrayList();  
  7.         Collections.addAll(list, a);  
  8.         return list;  
  9.     }  
  10. }  


測試代碼如下:
  1. import java.util.ArrayList;  
  2. import java.util.Arrays;  
  3. import java.util.List;  
  4. public class Test {  
  5.     @SuppressWarnings('unchecked')  
  6.     public static void main(String[] args) {  
  7.         List stooges = Arrays.asList('Larry''Moe''Curly');  
  8.         print(stooges);  
  9.         List<>> seasonsList = Arrays.asList(retrieveSeasonsList());  
  10.         print(seasonsList);  
  11.         /* 
  12.          * 自己實(shí)現(xiàn)一個asList方法,能夠添加和刪除。 
  13.          */  
  14.         List list = MyArrays.asList('Larry''Moe''Curly');  
  15.         list.add('Hello');  
  16.         print(list);  
  17.     }  
  18.     private static  void print(List list) {  
  19.         System.out.println(list);  
  20.     }  
  21.     private static List retrieveSeasonsList() {  
  22.         List seasonsList = new ArrayList();  
  23.         seasonsList.add('Spring');  
  24.         seasonsList.add('Summer');  
  25.         seasonsList.add('Autumn');  
  26.         seasonsList.add('Winter');  
  27.         return seasonsList;  
  28.     }  
  29. }  


輸出結(jié)果:

[Larry, Moe, Curly]
[[Spring, Summer, Autumn, Winter]]
[Larry, Moe, Curly, Hello]
本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點(diǎn)擊舉報(bào)
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
將java中數(shù)組轉(zhuǎn)換為ArrayList的方法實(shí)例(包括ArrayList轉(zhuǎn)數(shù)組)
集合異常java.lang.UnsupportedOperationException
正確認(rèn)識Arrays.asList方法
細(xì)數(shù) List 的10個坑,保證你一定遇到過!
Top 10 Mistakes Java Developers Make
關(guān)于 Java Collections 的幾個常見問題
更多類似文章 >>
生活服務(wù)
分享 收藏 導(dǎo)長圖 關(guān)注 下載文章
綁定賬號成功
后續(xù)可登錄賬號暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點(diǎn)擊這里聯(lián)系客服!

聯(lián)系客服