zoukankan      html  css  js  c++  java
  • Collection容器家族(AbstractSet源码详解)

    一、在Collection集合体系中的位置及概述

            AbstractSet抽象类属于Set集合分支的顶层类,它继承了AbstractCollection,实现了Set接口,先回顾一下Set接口,Set接口继承了Collection并没有进行扩展,AbstractCollection实现了Collection接口部分方法。

            这个抽象类中没有定义抽象方法,有且只有3个方法(实现其父类的)。分别为equals、hashCode、removeAll。

    二、AbstractSet方法详解

    1.删除指定集合的所有元素

        /**
         * 功能:删除指定集合的元素
         * 实现:
         * 1.如果指定集合c元素个数小于本集合,则遍历指定集合并删除现有集合的相同元素
         * 2.如果指定集合c元素个数大于本集合,则遍历本集合并删除现有集合于指定集合相容的元素
         */
        public boolean removeAll(Collection<?> c) {
            Objects.requireNonNull(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;
        }

    2.重写equals方法

            public boolean equals(Object o) {
            if (o == this)            //同一对象返回true
                return true;
     
            if (!(o instanceof Set))//不是Set返回false
                return false;
            Collection<?> c = (Collection<?>) o;
            if (c.size() != size())    //大小不一样返回false
                return false;
            try {
                return containsAll(c);    //当前集合是否包含待比较的对象集合,包含就返回ture不包含就返回false
            } catch (ClassCastException unused)   {
                return false;
            } catch (NullPointerException unused) {
                return false;
            }
        }

    3.重写hashCode方法

    
        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设计模式也无非就是抽象封装继承多态这四个特性的实现方式。我们把整个集合的框架用接口和抽象类分出层次,一方面是便于开发和理解。另一方面也便于我们扩展自己想要实现的东西,也避免了我们去实现一些不必要的东西。

  • 相关阅读:
    [leetcode] Longest Palindromic Substring
    [leetcode] Add Two Numbers
    [leetcode] Longest Substring Without Repeating Characters
    [leetcode] Median of Two Sorted Arrays
    [leetcode] Two Sum
    poj 2718 Smallest Difference
    AOJ 0525 Osenbei
    poj3190 stall revertation
    poj1328Radar Installation
    poj 2376 Cleaning Shifts
  • 原文地址:https://www.cnblogs.com/IdealSpring/p/11871200.html
Copyright © 2011-2022 走看看