JDK源码学习笔记-ArrayList\Vector

1、ArrayList容量变化的规则

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;
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
}

可以看出ArrayList扩容:[b](旧容量*3)/2 + 1,这样做的依据是什么?[/b]查资料也没找到答案,有知道的告诉下呗~
2、AyyayList指定位置的插入操作

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

同理,删除操作remove(int index)也是做了一次这样的拷贝。
3、Vector容量变化规则

private void ensureCapacityHelper(int minCapacity) {
int oldCapacity = elementData.length;
if (minCapacity > oldCapacity) {
Object[] oldData = elementData;
int newCapacity = (capacityIncrement > 0) ?
(oldCapacity + capacityIncrement) : (oldCapacity * 2);
if (newCapacity < minCapacity) {
newCapacity = minCapacity;
}
elementData = Arrays.copyOf(elementData, newCapacity);
}
}

当capacityIncrement变量大于0时则按照该变量值进行扩容,否则[color=darkred]翻倍扩容[/color](注意此处与ArrayList的区别)。
4、注意Vector中capacity()与size()的区别:
capacity()返回Vector当前容量;size()返回实际存储的元素长度。
5、Vector查重

public synchronized boolean retainAll(Collection<?> c) {
return super.retainAll(c);
}

ArrayList同样拥有!
5、AbstractList中的equals()方法

ListIterator e2 = ((List) o).listIterator();

所以下面这段代码:

ArrayList<Integer> temp1 = new ArrayList<Integer>();
Vector<Integer> temp2 = new Vector<Integer>();

Integer e1 = new Integer(1);
Integer e2 = new Integer(2);

temp1.add(e1);
temp1.add(e2);

temp2.add(e1);
temp2.add(e2);

if(temp2.equals(temp1)) {
System.out.println("equals");
}else {
System.out.println("not equals");
}

输出结果是“equals”!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值