java源码解读 集合类

1 A.contain(Object o);方法,由abstractCollection实现
public boolean contains(Object o) {
	Iterator<E> e = iterator();
	if (o==null) {
	    while (e.hasNext())
		if (e.next()==null)     //如果o为null,e.next==null,也返回true
		    return true;
	} else {
	    while (e.hasNext())     
		if (o.equals(e.next()))
		    return true;
	}
	return false;
    }


2 A.remove(Object o);方法,由abstractCollection实现
 public boolean remove(Object o) {
	Iterator<E> e = iterator();
	if (o==null) {
	    while (e.hasNext()) {
		if (e.next()==null) {
		    e.remove();      //如果o为null,e.next==null,也返回true
		    return true;
		}
	    }
	} else {
	    while (e.hasNext()) {
		if (o.equals(e.next())) {
		    e.remove();
		    return true;
		}
	    }
	}
	return false;
    }


3.A.retainAll(c)删除c中不包含的对象
 public boolean retainAll(Collection<?> c) {
	boolean modified = false;
	Iterator<E> e = iterator();
	while (e.hasNext()) {
	    if (!c.contains(e.next())) {
		e.remove();
		modified = true;
	    }
	}
	return modified;
    }


4.arraylist插入对象是,与初始建立的size需要比较,扩大size
    public void ensureCapacity(int minCapacity) {
	modCount++;
	int oldCapacity = elementData.length;
	if (minCapacity > oldCapacity) {
	    Object oldData[] = elementData;
	    int newCapacity = (oldCapacity * 3)/2 + 1;    //新建的size的大小
    	    if (newCapacity < minCapacity)
		newCapacity = minCapacity;    
            // minCapacity is usually close to size, so this is a win:
            elementData = Arrays.copyOf(elementData, newCapacity);
	}
    }


你可能感兴趣的:(java源码)