java_集合体系之Collection框架相关抽象类接口详解、源码——02

java_集合体系之Collection框架相关抽象类接口详解、源码——02


一:Collection相关接口、抽象类结构图


 


二:Collection相关

        1、接口简介:

                  Collection作为队列形式存储的集合的抽象接口 Collection  是一个被高度抽象出来的接口、提供基本的操作数据的行为、属性的定义、要求子类必须提供两个构造方法、一个无参构造方法、一个以另一个Collection为基础的构造方法。

        2、源码:

                 虽然Collection是一个接口、仅有方法的声明没有方法体、但是个人觉得知道源码中对各个方法的目的或者意义的说明对后面的理解还是很有必要的、同时在这里也不再将Collection的API一一列出来、会在后面的接口抽象类中标识列出、源码是一些方法的定义、

 

package com.chy.collection.core;

import java.util.Iterator;
/**
 * Collection  是一个被高度抽象出来的接口、是一个独立元素的序列、这些独立元素服从一条或者多条规则
 * 本身提供一类集合所具有的共同的方法、所有作为其子类的集合都不能直接实现他、而是应该实现他的子接口、
 * 并且必须要提供两个构造方法、一个无参构造方法、一个以一个集合为基础的有参构造方法。具体有什么规则
 * 在后面的具体的类的时候会有说明。
 * 
 * @author andyChen
 */
public interface Collection<E> extends Iterable<E> {

    /** 返回当前集合的大小、如果超过int的范围、则返回int的最大值*/
    int size();

    /** 标识当前Collection是否有元素、是返回true、否返回false*/
    boolean isEmpty();

    /** 当前Collection是否包含o、*/
    boolean contains(Object o);

    /** 返回当前Collection的包含所有元素的一个迭代器 */
    Iterator<E> iterator();

    /** 将当前Collection以一个Object数组的形式返回 */
    Object[] toArray();

    /** 将当前Collection中所有元素以一个与T相同类型的数组的形式返回*/
    <T> T[] toArray(T[] a);

    // Modification Operations

    /** 确保此 collection 包含指定的元素*/
    boolean add(E e);

    /**  从此 collection 中移除指定元素的单个实例,如果存在的话*/
    boolean remove(Object o);


    // Bulk Operations

    /** 如果此 collection 包含指定 collection 中的所有元素,则返回 true*/
    boolean containsAll(Collection<?> c);

    /** 将指定 collection 中的所有元素都添加到此 collection 中*/
    boolean addAll(Collection<? extends E> c);

    /**  移除此 collection 中那些也包含在指定 collection 中的所有元素(可选操作)*/
    boolean removeAll(Collection<?> c);

    /** 仅保留此 collection 中那些也包含在指定 collection 的元素、即求两个Collection的交集 */
    boolean retainAll(Collection<?> c);

    /** 移除此 collection 中的所有元素*/
    void clear();


    // Comparison and hashing

    /** 比较此 collection 与指定对象是否相等*/
    boolean equals(Object o);

    /** 返回此 collection 的哈希码值*/
    int hashCode();
}

三:AbstractCollection


        1、抽象类简介:

               AbstractCollection是一个实现Collection接口的抽象类、本身没有提供任何额外的方法、所有想要实现Collection接口的实现类都必须从AbstractCollection继承、他存在的意义就是大大减少编码的工作量、AbstractCollection中的方法都是从Collection接口中继承、除两个关键方法abstract Iterator<E> iterator();abstract int size();方法外都提供了简单的实现(这里要注意add()只是抛出异常、要求子类必须去实现、因为不同数据结构添加元素的方式不一致)、其他的方法都是通过Iterator的方法来实现的、所以在子类中要实现Iterator的方法、讲到Iterator才具体列举有哪些方法、这就是此类为什么能减少代码量的原因。

2、源码:

              API与Collection的完全相同、只是有简单实现、具体如何实现可见源码

package com.chy.collection.core;

import java.util.Arrays;
import java.util.Iterator;

/**
 * 此类提供 Collection 接口的骨干实现,以最大限度地减少了实现此接口所需的工作。 
 * 
 * 子类要继承此抽象类、
 * 1、必须提供两个构造方法、一个无参一个有参。
 * 2、必须重写抽象方法 Iterator<E> iterator();方法体中必须有hasNext()和next()两个方法、同时必须实现remove方法 用于操作集合中元素。
 * 3、一般要重写add方法、否则子类调用add方法会抛UnsupportedOperationException异常。
 * 子类通常要重写此类中的方法已得到更有效的实现、
 */

@SuppressWarnings("unchecked")
public abstract class AbstractCollection<E> implements Collection<E> {
    /**
     * 基础构造器
     */
    protected AbstractCollection() {
    }

    // Query Operations

    public abstract Iterator<E> iterator();

    public abstract int size();

    public boolean isEmpty() {
    	return size() == 0;
    }

    public boolean contains(Object o) {
		Iterator<E> e = iterator();
		if (o==null) {
		    while (e.hasNext())
			if (e.next()==null)
			    return true;
		} else {
		    while (e.hasNext())
			if (o.equals(e.next()))
			    return true;
		}
		return false;
    }

    public Object[] toArray() {
        // Estimate size of array; be prepared to see more or fewer elements
		Object[] r = new Object[size()];
	        Iterator<E> it = iterator();
		for (int i = 0; i < r.length; i++) {
		    if (! it.hasNext())	// fewer elements than expected
			return Arrays.copyOf(r, i);
		    r[i] = it.next();
		}
		return it.hasNext() ? finishToArray(r, it) : r;
    }

    public <T> T[] toArray(T[] a) {
        // Estimate size of array; be prepared to see more or fewer elements
        int size = 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;
    }

    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 / 2) + 1) * 3;
                if (newCap <= cap) { // integer overflow
		    if (cap == Integer.MAX_VALUE)
			throw new OutOfMemoryError
			    ("Required array size too large");
		    newCap = Integer.MAX_VALUE;
		}
		r = Arrays.copyOf(r, newCap);
	    }
	    r[i++] = (T)it.next();
        }
        // trim if overallocated
        return (i == r.length) ? r : Arrays.copyOf(r, i);
    }

    // Modification Operations

    public boolean add(E e) {
    	throw new UnsupportedOperationException();
    }

    public boolean remove(Object o) {
		Iterator<E> e = iterator();
		if (o==null) {
		    while (e.hasNext()) {
			if (e.next()==null) {
			    e.remove();
			    return true;
			}
		    }
		} else {
		    while (e.hasNext()) {
			if (o.equals(e.next())) {
			    e.remove();
			    return true;
			}
		    }
		}
		return false;
    }


    // Bulk Operations

    public boolean containsAll(Collection<?> c) {
		Iterator<?> e = c.iterator();
		while (e.hasNext())
		    if (!contains(e.next()))
			return false;
		return true;
    }

    public boolean addAll(Collection<? extends E> c) {
		boolean modified = false;
		Iterator<? extends E> e = c.iterator();
		while (e.hasNext()) {
		    if (add(e.next()))
			modified = true;
		}
		return modified;
    }

    public boolean removeAll(Collection<?> c) {
		boolean modified = false;
		Iterator<?> e = iterator();
		while (e.hasNext()) {
		    if (c.contains(e.next())) {
			e.remove();
			modified = true;
		    }
		}
		return modified;
    }

    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;
    }

    public void clear() {
		Iterator<E> e = iterator();
		while (e.hasNext()) {
		    e.next();
		    e.remove();
		}
    }


    //  String conversion

    public String toString() {
        Iterator<E> i = iterator();
		if (! i.hasNext())
		    return "[]";
	
		StringBuilder sb = new StringBuilder();
		sb.append('[');
		for (;;) {
		    E e = i.next();
		    sb.append(e == this ? "(this Collection)" : e);
		    if (! i.hasNext())
			return sb.append(']').toString();
		    sb.append(", ");
		}
    }
}


四:List


      1、接口简介:

           作为Collection的一个子接口、也是集合的一种、List是有序的队列、其中存放的每个元素都有索引、第一个元素的索引从0开始、与Set相比、List允许存放重复的元素。因其具有索引这一概念、所以相比于Collection接口、List多了根据索引操作元素的方法、具体可为“增删改查”、从前向后查找某元素的索引值、从后向前查找某元素的索引值、List特有的ListIterator和在指定的索引处添加一个Collection集合。

官方版:A List is a collection which maintains an ordering for its elements.Every element in the List has an index. Each element can thus be accessed byits index, with the first index being zero. Normally, Lists allow duplicateelements, as compared to Sets, where elements have to be unique.

        2、相对于Collection多提供的方法的源码
public interface List<E> extends Collection<E> {

    // Bulk Modification Operations

    /**
     * 将指定 collection 中的所有元素都插入到列表中的指定位置
     */
    boolean addAll(int index, Collection<? extends E> c);

    // Positional Access Operations

    /** 返回列表中指定位置的元素。*/
    E get(int index);

    /** 用指定元素替换列表中指定位置的元素*/
    E set(int index, E element);

    /** 在列表的指定位置插入指定元素*/
    void add(int index, E element);

    /** 移除列表中指定位置的元素*/
    E remove(int index);


    // Search Operations

    /** 返回此列表中第一次出现的指定元素的索引;如果此列表不包含该元素,则返回 -1*/
    int indexOf(Object o);

    /** 返回此列表中最后一次出现的指定元素的索引;如果此列表不包含该元素,则返回 -1*/
    int lastIndexOf(Object o);


    // List Iterators

    /**  返回此列表元素的列表迭代器*/
    ListIterator<E> listIterator();

    /** 返回列表中元素的列表迭代器(按适当顺序),从列表的指定位置开始*/
    ListIterator<E> listIterator(int index);

    // View

    /** 返回列表中指定的 fromIndex(包括 )和 toIndex(不包括)之间的部分视图*/
    List<E> subList(int fromIndex, int toIndex);
}


五:AbstractList


           1、抽象类简介:

                        同AbstractCollection定义相同、每个需要继承List的方法都不能从List直接继承、而是要通过AbstractList来实现、因List实现了Collection接口、所以为更一步简化编码、使得AbstractList继承AbstractCollection、这样AbstractList只需提供AbstractCollection中必须实现的方法的实现(具体是Iterator、add、size必须实现的方法、和一些为具有自己特色而重写的方法)List相对于Collection多提供的方法的实现即可。对于AbstractList的源码中、需要理解获取Iterator、ListIterator、

           2、源码
package com.chy.collection.core;

import java.util.AbstractList;
import java.util.AbstractSequentialList;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.RandomAccess;
import java.util.AbstractList.Itr;

/**
 * 此类提供 List 接口的骨干实现,以最大限度地减少实现“随机访问”数据存储(如数组)支持的该接口所需的工作。对于连续的访问数据(如链表),应优先使用 AbstractSequentialList,而不是此类。 
 * 
 * 1、若子类要使用set(int index, E e)则必须自己重新实现
 * 2、若子类要使用add(int index, E e)则必须自己重新实现
 * 3、若子类要使用remove(int index)则必须自己从新实现
 * 4、内部实现了iterator()方法、返回一个包含hasNext()、next()、remove()方法的Iterator。
 * 许多方法都是由内部类来实现的
 */

public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
    
	protected AbstractList() {
    }

    /**
     * 将指定元素追加到List集合结尾处
     */
    public boolean add(E e) {
		add(size(), e);
		return true;
    }

    abstract public E get(int index);

    public E set(int index, E element) {
    	throw new UnsupportedOperationException();
    }

    public void add(int index, E element) {
    	throw new UnsupportedOperationException();
    }

    public E remove(int index) {
    	throw new UnsupportedOperationException();
    }


    // Search Operations

    public int indexOf(Object o) {
		ListIterator<E> e = listIterator();
		if (o==null) {
		    while (e.hasNext())
			if (e.next()==null)
			    return e.previousIndex();
		} else {
		    while (e.hasNext())
			if (o.equals(e.next()))
			    return e.previousIndex();
		}
		return -1;
    }

    public int lastIndexOf(Object o) {
		ListIterator<E> e = listIterator(size());
		if (o==null) {
		    while (e.hasPrevious())
			if (e.previous()==null)
			    return e.nextIndex();
		} else {
		    while (e.hasPrevious())
			if (o.equals(e.previous()))
			    return e.nextIndex();
		}
		return -1;
    }


    // Bulk Operations

    public void clear() {
        removeRange(0, size());
    }

    public boolean addAll(int index, Collection<? extends E> c) {
		boolean modified = false;
		Iterator<? extends E> e = c.iterator();
		while (e.hasNext()) {
		    add(index++, e.next());
		    modified = true;
		}
		return modified;
    }


    // Iterators

    public Iterator<E> iterator() {
    	return new Itr();
    }

    public ListIterator<E> listIterator() {
    	return listIterator(0);
    }

    public ListIterator<E> listIterator(final int index) {
		if (index<0 || index>size())
		  throw new IndexOutOfBoundsException("Index: "+index);
	
		return new ListItr(index);
    }

    //fail-fast机制
    private class Itr implements Iterator<E> {
		/**
		 * 游标的位置、用于获取元素和标识是否遍历完毕
		 */
		int cursor = 0;
	
		/**
		 * 最后一次调用next或者previous返回的元素的下标、如果元素被删除则返回-1
		 */
		int lastRet = -1;
	
		/**
		 * 用于后面检测在执行Iterator过程中是否被动手脚的变量
		 */
		int expectedModCount = modCount;
	
		//是否还有下一个、从判断标准中可以看出、下边每遍历出一个元素cursor都会++
		public boolean hasNext() {
	            return cursor != size();
		}
	
		public E next() {
				//类私有方法、检测是否此类中元素被动过
	            checkForComodification();
		    try {
		    	//获取下一个元素、将返回的index元素的下标记录下来、同时cursor自增1
				E next = get(cursor);
				lastRet = cursor++;
				return next;
			} catch (IndexOutOfBoundsException e) {
				checkForComodification();
				throw new NoSuchElementException();
		    }
		}
	
		//移除当前遍历到的元素
		public void remove() {
		    if (lastRet == -1)
		    	throw new IllegalStateException();
	        checkForComodification();
		    try {
		    	//调用当前的remove删除最后被遍历到的元素、在next()方法中记录了此元素的idnex
				AbstractList.this.remove(lastRet);
				
				//将cursor--、继续遍历下一个
				if (lastRet < cursor)
				    cursor--;
				lastRet = -1;
				expectedModCount = modCount;
		    } catch (IndexOutOfBoundsException e) {
		    	throw new ConcurrentModificationException();
		    }
		}
		/**
		 * 检测是否触发fail-fast机制
		 */
		final void checkForComodification() {
		    if (modCount != expectedModCount)
				throw new ConcurrentModificationException();
		}
    }

    private class ListItr extends Itr implements ListIterator<E> {
    	
    	//构造方法、初始化第一个被读取的元素的下标
    	ListItr(int index) {
    	    cursor = index;
    	}
    	
    	//当前listIterator中cursor指向的元素是否还有上一个元素
    	public boolean hasPrevious() {
    	    return cursor != 0;
    	}

    	//获取当前ListIterator中cursor指向的元素
        public E previous() {
            checkForComodification();
            try {
            	//获取cursor上一个元素的
                int i = cursor - 1;
                E previous = get(i);
                lastRet = cursor = i;
                return previous;
            } catch (IndexOutOfBoundsException e) {
                checkForComodification();
                throw new NoSuchElementException();
            }
        }

    	public int nextIndex() {
    	    return cursor;
    	}

    	public int previousIndex() {
    	    return cursor-1;
    	}

    	public void set(E e) {
    	    if (lastRet == -1)
    		throw new IllegalStateException();
                checkForComodification();

    	    try {
	    		AbstractList.this.set(lastRet, e);
	    		expectedModCount = modCount;
    	    } catch (IndexOutOfBoundsException ex) {
    		throw new ConcurrentModificationException();
    	    }
    	}

    	public void add(E e) {
                checkForComodification();

    	    try {
    		AbstractList.this.add(cursor++, e);
    		lastRet = -1;
    		expectedModCount = modCount;
    	    } catch (IndexOutOfBoundsException ex) {
    		throw new ConcurrentModificationException();
    	    }
    	}
    }

    public List<E> subList(int fromIndex, int toIndex) {
        return (this instanceof RandomAccess ?
                new RandomAccessSubList<E>(this, fromIndex, toIndex) :
                new SubList<E>(this, fromIndex, toIndex));
    }

    // Comparison and hashing

    public boolean equals(Object o) {
		if (o == this)
		    return true;
		if (!(o instanceof List))
		    return false;
	
		ListIterator<E> e1 = listIterator();
		ListIterator e2 = ((List) o).listIterator();
		while(e1.hasNext() && e2.hasNext()) {
		    E o1 = e1.next();
		    Object o2 = e2.next();
		    if (!(o1==null ? o2==null : o1.equals(o2)))
			return false;
		}
		return !(e1.hasNext() || e2.hasNext());
    }

    public int hashCode() {
		int hashCode = 1;
		Iterator<E> i = iterator();
		while (i.hasNext()) {
		    E obj = i.next();
		    hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());
		}
		return hashCode;
    }

    protected void removeRange(int fromIndex, int toIndex) {
        ListIterator<E> it = listIterator(fromIndex);
        for (int i=0, n=toIndex-fromIndex; i<n; i++) {
            it.next();
            it.remove();
        }
    }

    protected transient int modCount = 0;
}

class SubList<E> extends AbstractList<E> {
    private AbstractList<E> l;
    private int offset;
    private int size;
    private int expectedModCount;

    SubList(AbstractList<E> list, int fromIndex, int toIndex) {
        if (fromIndex < 0)
            throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
        if (toIndex > list.size())
            throw new IndexOutOfBoundsException("toIndex = " + toIndex);
        if (fromIndex > toIndex)
            throw new IllegalArgumentException("fromIndex(" + fromIndex +
                                               ") > toIndex(" + toIndex + ")");
        l = list;
        offset = fromIndex;
        size = toIndex - fromIndex;
        expectedModCount = l.modCount;
    }

    public E set(int index, E element) {
        rangeCheck(index);
        checkForComodification();
        return l.set(index+offset, element);
    }

    public E get(int index) {
        rangeCheck(index);
        checkForComodification();
        return l.get(index+offset);
    }

    public int size() {
        checkForComodification();
        return size;
    }

    public void add(int index, E element) {
        if (index<0 || index>size)
            throw new IndexOutOfBoundsException();
        checkForComodification();
        l.add(index+offset, element);
        expectedModCount = l.modCount;
        size++;
        modCount++;
    }

    public E remove(int index) {
        rangeCheck(index);
        checkForComodification();
        E result = l.remove(index+offset);
        expectedModCount = l.modCount;
        size--;
        modCount++;
        return result;
    }

    protected void removeRange(int fromIndex, int toIndex) {
        checkForComodification();
        l.removeRange(fromIndex+offset, toIndex+offset);
        expectedModCount = l.modCount;
        size -= (toIndex-fromIndex);
        modCount++;
    }

    public boolean addAll(Collection<? extends E> c) {
        return addAll(size, c);
    }

    public boolean addAll(int index, Collection<? extends E> c) {
        if (index<0 || index>size)
            throw new IndexOutOfBoundsException(
                "Index: "+index+", Size: "+size);
        int cSize = c.size();
        if (cSize==0)
            return false;

        checkForComodification();
        l.addAll(offset+index, c);
        expectedModCount = l.modCount;
        size += cSize;
        modCount++;
        return true;
    }

    public Iterator<E> iterator() {
        return listIterator();
    }

    public ListIterator<E> listIterator(final int index) {
        checkForComodification();
        if (index<0 || index>size)
            throw new IndexOutOfBoundsException(
                "Index: "+index+", Size: "+size);

        return new ListIterator<E>() {
            private ListIterator<E> i = l.listIterator(index+offset);

            public boolean hasNext() {
                return nextIndex() < size;
            }

            public E next() {
                if (hasNext())
                    return i.next();
                else
                    throw new NoSuchElementException();
            }

            public boolean hasPrevious() {
                return previousIndex() >= 0;
            }

            public E previous() {
                if (hasPrevious())
                    return i.previous();
                else
                    throw new NoSuchElementException();
            }

            public int nextIndex() {
                return i.nextIndex() - offset;
            }

            public int previousIndex() {
                return i.previousIndex() - offset;
            }

            public void remove() {
                i.remove();
                expectedModCount = l.modCount;
                size--;
                modCount++;
            }

            public void set(E e) {
                i.set(e);
            }

            public void add(E e) {
                i.add(e);
                expectedModCount = l.modCount;
                size++;
                modCount++;
            }
        };
    }

    public List<E> subList(int fromIndex, int toIndex) {
        return new SubList<E>(this, fromIndex, toIndex);
    }

    private void rangeCheck(int index) {
        if (index<0 || index>=size)
            throw new IndexOutOfBoundsException("Index: "+index+
                                                ",Size: "+size);
    }

    private void checkForComodification() {
        if (l.modCount != expectedModCount)
            throw new ConcurrentModificationException();
    }
}

class RandomAccessSubList<E> extends SubList<E> implements RandomAccess {
    RandomAccessSubList(AbstractList<E> list, int fromIndex, int toIndex) {
        super(list, fromIndex, toIndex);
    }

    public List<E> subList(int fromIndex, int toIndex) {
        return new RandomAccessSubList<E>(this, fromIndex, toIndex);
    }
}

 

六:Iterable、Iterator、ListIterator


         1、Iterable接口说明及源码

                Iterable接口中只有一个方法就是返回一个有序元素序列的迭代器Iterator

public interface Iterable<T> {

    /** 返回一个元素序列的迭代器 */
    Iterator<T> iterator();
	
}

         2、Iterator接口说明及源码

                 是集合依赖的接口、每个集合类或者其父类都必须实现获取Iterator的方法、同时要提供Iterator中方法的实现、用于遍历和作为一些方法的实现。

public interface Iterator<E> {

    boolean hasNext();

 
    E next();

 
    void remove();
}


        3、ListIterator接口说明及源码

                ListIterator继承Iterator、用于提供额外的几个方法、用于迭代List集合中的元素。

public interface ListIterator<E> extends Iterator<E> {
    // Query Operations

    /**
     * 以正向遍历列表时,如果列表迭代器有多个元素,则返回 true(换句话说,如果 next 返回一个元素而不是抛出异常,则返回 true)。
     */
    boolean hasNext();

    /**
     * 返回列表中的下一个元素。
     */
    E next();

    /**
     *  如果以逆向遍历列表,列表迭代器有多个元素,则返回 true。
     */
    boolean hasPrevious();

    /**
     * 返回列表中的前一个元素。
     */
    E previous();

    /**
     * 返回对 next 的后续调用所返回元素的索引。
     */
    int nextIndex();

    /**
     * 返回对 previous 的后续调用所返回元素的索引。
     */
    int previousIndex();


    // Modification Operations

    /**
     * 从列表中移除由 next 或 previous 返回的最后一个元素(可选操作)。
     */
    void remove();

    void set(E e);

    void add(E e);
}


六:Set


            1、接口简介:

                        Set、作为Collection的一个子类、与List相比、其不允许有重复元素出现、存放的元素没有索引一说、其API与Collection完全相同、只是对方法的定义不同

         2、源码不再乱贴

七:AbstractSet


               1、抽象类简介:

                            同AbstractList很相似、因Set继承与Collection接口、其也继承AbstractCollection抽象类、由于Set的特性、他不像AbstractList一样新增了有关索引的操作方法、他没有添加任何方法、仅仅是实现了equals、hashCode、removeAll(Collection<?> c)方法的实现。注意:他不像AbstractList、内部提供了实现获取Iterator的方法、他要求继承他的子类去实现获取Iterator的方法。

              2、源码
package com.chy.collection.core;

import java.util.Iterator;

/**
 * 此类提供 Set 接口的骨干实现,从而最大限度地减少了实现此接口所需的工作。
 * 此类并没有重写 AbstractCollection 类中的任何实现。它仅仅添加了 equals 和 hashCode 的实现。
 */
@SuppressWarnings("unchecked")
public abstract class AbstractSet<E> extends AbstractCollection<E> implements Set<E> {
    protected AbstractSet() {
    }

    // Comparison and hashing

    public boolean equals(Object o) {
	if (o == this)
	    return true;

	if (!(o instanceof Set))
	    return false;
	Collection c = (Collection) o;
	if (c.size() != size())
	    return false;
        try {
            return containsAll(c);
        } catch (ClassCastException unused)   {
            return false;
        } catch (NullPointerException unused) {
            return false;
        }
    }

    public int hashCode() {
	int h = 0;
	Iterator<E> i = iterator();
	while (i.hasNext()) {
	    E obj = i.next();
            if (obj != null)
                h += obj.hashCode();
        }
	return h;
    }

    public boolean removeAll(Collection<?> c) {
        boolean modified = false;

        if (size() > c.size()) {
            for (Iterator<?> i = c.iterator(); i.hasNext(); )
                modified |= remove(i.next());
        } else {
            for (Iterator<?> i = iterator(); i.hasNext(); ) {
                if (c.contains(i.next())) {
                    i.remove();
                    modified = true;
                }
            }
        }
        return modified;
    }
}


 

  • 16
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值