Java ArrayList add(index,element) 方法插入元素到數組指定位置__Java

來源:互聯網
上載者:User
Java ArrayList add(index,element) 方法插入元素到數組指定位置 原創  2013年10月10日 13:09:37 標籤: java 24540

今天在開發項目的過程中,準備使用ArrayList 的 add(index,element) 來插入元素,天真的以為這樣能給list排序

簡略代碼如下:

List list = new ArrayList(50); list.add(0,element); list.add(2,element); list.add(1,element);

編譯運行之後拋出了exception,百思不得其解,等到看了源碼之後才發現原因,ArrayList  add(index,element)方法源碼:


public void add(int index, E element) {    if (index > size || index < 0)        throw new IndexOutOfBoundsException(        "Index: "+index+", Size: "+size);      ensureCapacity(size+1);  // Increments modCount!!    System.arraycopy(elementData, index, elementData, index + 1,             size - index);    elementData[index] = element;    size++;   }

從代碼中可以看出,當數組中的元素個數(size)小於index的時候,此方法是會拋出異常的。

所以此方法只適用於想要插入的位置小於數組中實際元素個數的時候才有作用。

也就是說,讓list裡面沒有元素時,想通過插入元素到指定位置來達到排序的效果是不可行的。

聯繫我們

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