---
title: "JDK源码学习笔记-ArrayList\\Vector"
author: "kayban"
date: "2011-09-22T15:05:37Z"
tags: []
categories: ["编程语言"]
slug: "jdk-arraylist-vector"
draft: false
lastmod: "2011-09-22T15:11:52Z"
id: 1177981
url: "https://ban.iteye.com/blog/1177981"
---

1、ArrayList容量变化的规则

```java

   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扩容：**（旧容量*3）/2 + 1，这样做的依据是什么？**查资料也没找到答案，有知道的告诉下呗~
2、AyyayList指定位置的插入操作

```java

    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容量变化规则

```java

    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时则按照该变量值进行扩容，否则<span style="color:darkred">翻倍扩容</span>（注意此处与ArrayList的区别）。
4、注意Vector中capacity()与size()的区别：
capacity()返回Vector当前容量；size()返回实际存储的元素长度。
5、Vector查重

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

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

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

```

所以下面这段代码：

```java

        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”!