Java基礎,java基礎知識總結

來源:互聯網
上載者:User

Java基礎,java基礎知識總結


      集合包括常用的ArrayList、HashMap、HashSet,也有不常用的Stack、Queue,有安全執行緒的Vector、HashTable,也有線程不安全的LinkedList、TreeMap等。

  • Arraylist                                                         

  ArrayList是實現List介面的動態數組,初始容量10,即數組大小。在每次向容器中增加元素的同時都會進行容量檢查,當快溢出時,就會進行擴容操作(資料向新數組的重新拷貝)。不是同步的,多線程中使用,最好在建立的時候保證同步。

  例如  :

 List list = Collections.synchronizedList(new ArrayList()); 

  建立:即建立一個transient修飾的數組。

  新增:

    方法:add(E e)、add(int index, E element)、addAll(Collection<? extends E> c)、addAll(int index, Collection<? extends E> c)、set(int index, E element)

    通常會先一步檢測容器大小,查看是否需要擴容。調用ensureCapacity()方法對ArrayList集合進行擴容操作

public void ensureCapacity(int minCapacity) {        //修改計時器        modCount++;        //ArrayList容量大小        int oldCapacity = elementData.length;        /*         * 若當前需要的長度大於當前數組的長度時,進行擴容操作         */        if (minCapacity > oldCapacity) {            Object oldData[] = elementData;            //計算新的容量大小,為當前容量的1.5倍            int newCapacity = (oldCapacity * 3) / 2 + 1;            if (newCapacity < minCapacity)                newCapacity = minCapacity;            //數組拷貝,產生新的數組            elementData = Arrays.copyOf(elementData, newCapacity);        }    }

    若為指定index位置插入元素add(int index, E element),會調用System.arraycopy()方法,目的就是將index位置空出來以供新資料插入,這裡需要進行數組資料的右移,這是非常麻煩和耗時的,所以如果指定的資料集合需要進行大量插入操作,推薦使用LinkedList。

  刪除:

    方法:remove(int index)、remove(Object o)、removeRange(int fromIndex, int toIndex)、removeAll()

    刪除元素後,會調用System.arraycopy(...)方法對剩餘元素位置進行調整

  擷取:

    方法:get(int index)

    由於ArrayList是動態數組,所以我們完全可以根據下標來擷取ArrayList中的元素,而且速度還比較快,故ArrayList適於隨機訪問

  • LinkedList

  LinkedList是實現List介面的鏈表,插入和刪除時優於ArrayList,而隨機訪問則比ArrayList遜色些。

 



 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.