JDK1.7源码解读之--AbstractCollection

本文详细解析了JDK1.7中AbstractCollection类的实现细节,包括其构造方法、常用方法如iterator()、size()、isEmpty()等的功能与实现原理,以及如何处理数组扩容等问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在解读JDK1.7源码,就自己的理解随便说下,若有不对的地方,欢迎大家提供宝贵意见。

1.AbstractCollection集成关系如图所示:

           

2.AbstractCollection 变量和方法解读:

protected AbstractCollection() {}   //定义构造方法
public abstract Iterator<E> iterator(); //返回在此 collection 中的元素上进行迭代的迭代器。
public abstract int size();  //返回集合元素数。如果元素数大于Integer.MAX_VALUE,则返回 Integer.MAX_VALUE。
//如果此 collection 不包含元素,则返回 true。
public boolean isEmpty() {  
    return size() == 0;
} 
//如果此 collection 包含指定的元素,则返回 true。
public boolean contains(Object o) {  
    Iterator<E> it = iterator();
    if (o==null) {
        while (it.hasNext())
            if (it.next()==null)
                return true;
    } else {
        while (it.hasNext())
            if (o.equals(it.next()))
                return true;
        }
    return false;
} 
//将集合转为数组
public Object[] toArray() {
    //估计数组的大小;准备好看到更多或更少的元素
    Object[] r = new Object[size()];
    Iterator<E> it = iterator();
    for (int i = 0; i < r.length; i++) {
        if (! it.hasNext()) // 比预期的元素少,即size大小少于迭代器中的元素个数,则返回r数组的前i个元素
            return Arrays.copyOf(r, i);
        r[i] = it.next();
    }
    //如果迭代器的元素个数多于size大小,则执行finishToArray(r, it) ;反之如果迭代器中的元素个数和r的长度相等,则返回r数组。
    return it.hasNext() ? finishToArray(r, it) : r;
}
//数组最大容量
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
//返回转换后的数组
private static <T> T[] finishToArray(T[] r, Iterator<?> it) {
    int i = r.length; //获取集合长度
    while (it.hasNext()) { 
        int cap = r.length;
        if (i == cap) {
             int newCap = cap + (cap >> 1) + 1; //新的数组容量变为原来的1.5倍加1
            //内存溢出实现
            if (newCap - MAX_ARRAY_SIZE > 0)   //如果新的数组容量大于MAX_ARRAY_SIZE,则对该数组的容量进行扩容处理
                newCap = hugeCapacity(cap + 1);  //扩容后的数组容量
            r = Arrays.copyOf(r, newCap);   //实现扩容
        }
        r[i++] = (T)it.next(); //将迭代器中的元素放入数组中
    }
    //如果i == r.length相等,返回r数组;反之(r.length>i),则取r数组中的前i个元素
    return (i == r.length) ? r : Arrays.copyOf(r, i);
}
//数组容量大小(扩大)
private static int hugeCapacity(int minCapacity) {
    //由于minCapacity = cap + 1;当cap为Integer.MAX_VALUE时,加1会变成负数,则抛出OutOfMemoryError
    if (minCapacity < 0) // overflow
            throw new OutOfMemoryError("Required array size too large");
    //当minCapacity > MAX_ARRAY_SIZE,则返回Integer.MAX_VALUE;反之返回MAX_ARRAY_SIZE
    return (minCapacity > MAX_ARRAY_SIZE) ?Integer.MAX_VALUE :MAX_ARRAY_SIZE;
}
//将集合转为数组(带参数)
public <T> T[] toArray(T[] a) {
    // Estimate size of array; be prepared to see more or fewer elements
    int size = size();
    //判断a数组的长度和AbstractCollection集合size()大小,如果数组长达大于等于集合的size(),测返回a数组;
    //反之,根据a数组的类型,构造了一个对应类型的,长度跟AbstractCollection的size()一致的空数组
    T[] r = a.length >= size ? a :
                  (T[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);
    Iterator<E> it = iterator();

    for (int i = 0; i < r.length; i++) {
        if (! it.hasNext()) { // fewer elements than expected
            if (a != r)
                return Arrays.copyOf(r, i);
            r[i] = null; // null-terminate
            return r;
        }
        r[i] = (T)it.next();
    }
    return it.hasNext() ? finishToArray(r, it) : r;
}
//AbstractCollection的add()方法不支持添加单个元素,添加则报错(如果子类是可添加的数据结构,需要自己实现add(E)方法)
public boolean add(E e) {
    throw new UnsupportedOperationException();
}
//删除某元素
//首先集合中存在该元素的情况:判断要移除的元素是否为空,
//    为空,则使用集合迭代器,移除集合中所有的空元素,如果存在空,返回true
//    不为空,则集合迭代器中所有元素和要移除的元素比较,存在则移除元素,返回true
//其次集合中不存在该元素,则返回false
public boolean remove(Object o) {
    Iterator<E> it = iterator();
    if (o==null) {
        while (it.hasNext()) {
            if (it.next()==null) {
                it.remove();
                return true;
            }
        }
    } else {
        while (it.hasNext()) {
            if (o.equals(it.next())) {
                it.remove();
                return true;
            }
        }
    }
    return false;
}
//判断AbstractCollection集合是否包含集合c(即集合c中的每一个元素在AbstractCollection集合中是否存在)
public boolean containsAll(Collection<?> c) {
    for (Object e : c)
	 if (!contains(e))
	      return false;
    return true;
}
//向AbstractCollection集合中添加集合c(即向集合中添加集合c中的每一个元素,AbstractCollection(子类)集合改变,才返回true)
public boolean addAll(Collection<? extends E> c) {
    boolean modified = false;
    for (E e : c)
	if (add(e))
            modified = true;
    return modified;
}
//移除集合中所有在集合c中有的元素()
public boolean removeAll(Collection<?> c) {
    boolean modified = false;
    Iterator<?> it = iterator();
    while (it.hasNext()) {
        if (c.contains(it.next())) {
            it.remove();
            modified = true;
        }
    }
    return modified;
}
//移除集合中所有的不存在于集合c中的元素
public boolean retainAll(Collection<?> c) {
    boolean modified = false;
    Iterator<E> it = iterator();
    while (it.hasNext()) {
        if (!c.contains(it.next())) {
            it.remove();
            modified = true;
        }
    }
    return modified;
}
//移除集合中所有的元素
public void clear() {
    Iterator<E> it = iterator();
    while (it.hasNext()) {
        it.next();
        it.remove();
    }
}
//将集合转为字符串形式
public String toString() {
    Iterator<E> it = iterator();
    if (! it.hasNext())
        return "[]";

    StringBuilder sb = new StringBuilder();
    sb.append('[');
    for (;;) {
        E e = it.next();
        sb.append(e == this ? "(this Collection)" : e);
        if (! it.hasNext())
            return sb.append(']').toString();
        sb.append(',').append(' ');
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值