Map接口与抽象类

一.Map部分结构图

Map接口与抽象类_第1张图片
image.png

二.Map接口

Map接口与抽象类_第2张图片
image.png

三.AbstractMap抽象类

  • 供子类实现的方法:put,entrySet
  • Map的增删改查都是通过获取Iterator> i = entrySet().iterator()遍历实现的,以查询为例
  public V get(Object key) {
        Iterator> i = entrySet().iterator();
        if (key==null) {
            while (i.hasNext()) {
                Entry e = i.next();
                if (e.getKey()==null)
                    return e.getValue();
            }
        } else {
            while (i.hasNext()) {
                Entry e = i.next();
                if (key.equals(e.getKey()))
                    return e.getValue();
            }
        }
        return null;
    }

  • keySet()与values()
    • keySet()是new 一个实现了迭代器的AbstractSet()返回,values()是 new一个实现迭代器的AbstractCollection()返回,因而可以使用迭代器遍历map元素。
    • 由于key和value存储方式只实现各个线程内存的可见性(volatile),但无法保证原子性。
transient volatile Set        keySet = null;
transient volatile Collection values = null;
 public Collection values() {
        if (values == null) {
            values = new AbstractCollection() {
                public Iterator iterator() {
                    return new Iterator() {
                        private Iterator> i = entrySet().iterator();
                        public boolean hasNext() {
                            return i.hasNext();
                        }
                        public V next() {
                            return i.next().getValue();
                        }
                        public void remove() {
                            i.remove();
                        }
            };
        }
        return values;
    }

四.SortedMap接口

  • 相交Map附加方法:
  • 进一步提供关于键的总体排序 的 Map。该映射是根据其键的自然顺序进行排序的,或者根据在创建有序映射时提供的 Comparator 进行排序。对有序映射的 collection 视图(由 entrySet、keySet和 values 方法返回)进行迭代时,此顺序就会反映出来。要采用此排序方式,还需要提供一些其他操作(此接口是 SortedSet 的对应映射)。
    Map接口与抽象类_第3张图片
    image.png

五.NavigableMap接口

  • 扩展的 SortedMap,具有了针对给定搜索目标返回最接近匹配项的导航方法。方法 lowerEntry、floorEntry、ceilingEntry 和 higherEntry 分别返回与小于、小于等于、大于等于、大于给定键的键关联的 Map.Entry 对象,如果不存在这样的键,则返回 null。类似地,方法 lowerKey、floorKey、ceilingKey和 higherKey只返回关联的键。所有这些方法是为查找条目而不是遍历条目而设计的
  • 此接口还定义了 firstEntry、pollFirstEntry、lastEntry 和 pollLastEntry 方法,它们返回和/或移除最小和最大的映射关系(如果存在),否则返回 null


    Map接口与抽象类_第4张图片
    image.png

六.ConcurrentMap

  • 提供其他原子 putIfAbsent、remove、replace方法的 Map。
    Map接口与抽象类_第5张图片
    image.png

七·.ConcurrentNavigableMap( extends ConcurrentMap, NavigableMap)

  • 供其他原子 putIfAbsent、remove、replace方法的 Map;支持 NavigableMap 操作,且以递归方式支持其可导航子映射的 ConcurrentMap。
    Map接口与抽象类_第6张图片
    image.png

你可能感兴趣的:(Map接口与抽象类)