日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java集合的添加方法_深入理解java集合框架之---------Arraylist集合 -----添加方法

發布時間:2023/12/2 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java集合的添加方法_深入理解java集合框架之---------Arraylist集合 -----添加方法 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Arraylist集合 -----添加方法

1、add(E e) 向集合中添加元素

/**

* 檢查數組容量是否夠用

* @param minCapacity

*/

public void ensureCapacity(int minCapacity){

modCount++;

int oldCapacity = elementData.length;

if(minCapacity > oldCapacity){

Object oldData[] = elementData;

int newCapacity = (oldCapacity * 3)/2+1;

if(newCapacity < minCapacity){

newCapacity = minCapacity;

elementData = Arrays.copyOf(elementData, newCapacity);

}

}

}

/* (non-Javadoc)

* 向ArrayList中添加元素

* @see java.util.AbstractList#add(java.lang.Object)

*/

public boolean add(E e){

ensureCapacity(size+1);

elementData[size++] = e;

return true;

}

2、add(int? index ,E e) 向集合的指定索引處添加元素

/**

* Inserts the specified element at the specified position in this

* list. Shifts the element currently at that position (if any) and

* any subsequent elements to the right (adds one to their indices).

*

* @param index index at which the specified element is to be inserted

* @param element element to be inserted

* @throws IndexOutOfBoundsException {@inheritDoc}

*/

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++;

}

3、addAll(Collection< ? extends E> c) 添加集合

/*

* 添加元素集合

* (non-Javadoc)

* @see java.util.AbstractCollection#addAll(java.util.Collection)

*/

public boolean addAll(Collection extends E> c){

Object[] a = c.toArray();

int numNew = a.length;

ensureCapacity(size+numNew);

System.arraycopy(a, 0, elementData, size, numNew);

size+=numNew;

return numNew!=0;

}

4、addAll(int index, Collection extends E> c); 在指定索引出添加集合

public boolean addAll(int index, Collection extends E> c) {

if (index > size || index < 0)

throw new IndexOutOfBoundsException(

"Index: " + index + ", Size: " + size);

Object[] a = c.toArray();

int numNew = a.length;

ensureCapacity(size + numNew); // Increments modCount

int numMoved = size - index;

if (numMoved > 0)

System.arraycopy(elementData, index, elementData, index + numNew,

numMoved);

System.arraycopy(a, 0, elementData, index, numNew);

size += numNew;

return numNew != 0;

}

總結

以上是生活随笔為你收集整理的java集合的添加方法_深入理解java集合框架之---------Arraylist集合 -----添加方法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。