`
kayban
  • 浏览: 38200 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

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扩容:(旧容量*3)/2 + 1,这样做的依据是什么?查资料也没找到答案,有知道的告诉下呗~
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时则按照该变量值进行扩容,否则翻倍扩容(注意此处与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”!
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics