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

本文详细介绍了ArrayList集合的四个关键添加方法:add(E), add(int index, E), addAll(), addAll(int index, Collection),包括容量调整、数组复制等内部机制。深入理解这些方法有助于高效使用ArrayList进行数据管理。
摘要由CSDN通过智能技术生成

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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值