java source code - AbstractSet

AbstractSet abstract class is part of a collection of branch Set top class, it inherits AbstractCollection, implements the Set interface.

  public abstract class AbstractSet<E> extends AbstractCollection<E> implements Set<E>

This abstract class defines the abstract methods are not, and only three methods (implemented parent class). They were equals, hashCode, removeAll.

1. Remove all the elements of the specified collection

    public boolean removeAll(Collection<?> c) {
        Objects.requireNonNull(c);
        boolean modified = false;
 
        IF (size ()> c.size ()) { // if the number is greater than the specified number of the sets of the present set of elements c, c is set to traverse the same set and delete existing elements
             for (the Iterator <?> = I c.iterator (); i.hasNext ();)
                modified |= remove(i.next());
        } The else {     // Otherwise, if the present number is less than the specified number of the sets c collection element, the collection traverse the same set of c and delete existing elements
             for (the Iterator I = <?> Iterator (); i.hasNext ();) {
                 IF (c.contains (i.next ())) {
                    i.remove();
                    modified = true;
                }
            }
        }
        return modified;
    }

2. override the equals method

public  Boolean the equals (Object O) {
         IF (O == the this )             // same object returns to true 
            return  to true ;
 
        IF (! (O instanceof Set)) // not Set return false 
            return  false ;
        Collection <?> = C (<?> Collection ) O;
         IF (! C.size () = size ())     // sample sizes returns to false 
            return  to false ;
         the try {
             return containsAll (C);     // current set whether contains a collection of objects to be compared, comprise not contain ture returns returns to false 
        } the catch (a ClassCastException unused) {
             return  to false ;
        } catch (NullPointerException unused) {
            return false;
        }
    }

3. override the hashCode method

public int hashCode() {
        int h = 0;                    //它的hashCode算法是把所有的元素的hashCode值相加 返回
        Iterator<E> i = iterator();
        while (i.hasNext()) {
            E obj = i.next();        
            if (obj != null)
                h += obj.hashCode();
        }
        return h;
    }

总结
  其实关于abstratSet抽象类、还有这些集合的接口啊,没有什么可以叙述的,具体为什么这么设计,说白了就是面向对象设计,OOD,用面向对象的思维来看待JDK中的源码,设计无非就是使用 抽象、 封装、 继承、 多态这四个特性去做事情,我们学习的23种java设计模式也无非就是抽象封装继承多态这四个特性的实现方式。

  我们把整个集合的框架用接口和抽象类分出层次,一方面是便于开发和理解。另一方面也便于我们扩展自己想要实现的东西,也避免了我们去实现一些不必要的东西。

Guess you like

Origin www.cnblogs.com/FondWang/p/11921538.html