Java集合框架06--Map架构与源码分析

原文链接:http://blog.csdn.net/eson_15/article/details/51150033

        前几节我们对Collection以及Collection中的List部分进行了分析,Collection中还有个Set,由于Set是基于Map实现的,所以这里我们先分析Map,后面章节再继续学习Set。首先我们看下Map架构图:

《Java集合框架06--Map架构与源码分析》

        从图中可以看出:

        1. Map是一个接口,Map中存储的内容是键值对(key-value)

        2. 为了方便,我们抽象出AbstractMap类来让其他类继承,该类实现了Map中的大部分API,其他Map的具体实现就可以通过直接继承AbatractMap类即可。

        3. SortedMap也是一个接口,它继承与Map接口。SortedMap中的内容与Map中的区别在于,它是有序的键值对,里面排序的方法是通过比较器(Comparator)实现的。

        4. NavigableMap也是一个接口,它继承与SortedMap接口,所以它肯定也是有序的,另外,NavigableMap还有一些导航的方法:如获取“大于或等于某个对象的键值对”等等。

        5. 再往下就是具体实现类了,TreeMap继承与AbstractMap,同时实现了NavigableMap接口。因此,TreeMap中的内容是有序键值对

        6. HashMap仅仅是继承了AbstractMap,并没有实现NavigableMap接口。因此,HashMap的内容仅是键值对而已,不保证有序

        7. WeakHashMap也是仅仅继承了AbstractMap,它和HashMap的区别是键类型不同,WeakHashMap的键是弱键

        8. HashTable虽然不是继承与AbstractMap,但是它继承与Dictionary(Dictionary也是键值对的接口),而且也实现了Map接口。因此,HashTable的内容也是键值对,且不保证顺序。但是和HashMap相比,HashTable是线程安全的,而且它支持通过Enumeration去遍历。

        本节主要是讨论一下Map的架构,然后对各个接口和抽象类做一些介绍,研究一些源码,至于像TreeMap,HashMap等具体实现类的源码,我们在后续章节详细的研究。


1.Map

      

        Map的定义及其API如下:

[java]
view plain
copy
print
?

  1. package java.util;  
  2.   
  3. public interface Map<K,V> {  
  4.     boolean isEmpty();  
  5.     boolean containsKey(Object key);  
  6.     boolean containsValue(Object value);  
  7.     V get(Object key);  
  8.     V put(K key, V value);  
  9.     V remove(Object key);  
  10.     void putAll(Map<? extends K, ? extends V> m);  
  11.     void clear();  
  12.     Set<K> keySet(); //保存key的Set  
  13.     Collection<V> values(); //保存value的Collection  
  14.     Set<Map.Entry<K, V>> entrySet(); //保存Map.Entry的Set  
  15.     interface Entry<K,V> { //Map内部的一个接口,Entry中封装了key和value信息  
  16.         K getKey();  
  17.         V getValue();  
  18.         V setValue(V value);  
  19.         boolean equals(Object o);  
  20.         int hashCode();  
  21.     }  
  22.     boolean equals(Object o);  
  23.     int hashCode();  
  24.   
  25. }  
package java.util;

public interface Map<K,V> {
    boolean isEmpty();
    boolean containsKey(Object key);
    boolean containsValue(Object value);
    V get(Object key);
    V put(K key, V value);
    V remove(Object key);
    void putAll(Map<? extends K, ? extends V> m);
    void clear();
    Set<K> keySet(); //保存key的Set
    Collection<V> values(); //保存value的Collection
    Set<Map.Entry<K, V>> entrySet(); //保存Map.Entry的Set
    interface Entry<K,V> { //Map内部的一个接口,Entry中封装了key和value信息
        K getKey();
        V getValue();
        V setValue(V value);
        boolean equals(Object o);
        int hashCode();
    }
    boolean equals(Object o);
    int hashCode();

}

    由上面的源码可知:

    1. Map提供了一些接口分别用于返回键集、值集以及键值映射关系集。

        keySet()用于返回键的Set集合;

        values()用于返回值的Set集合;

        entrySet()用于返回键值集的Set集合,键值信息封装在Entry中。

    2. Map还对外提供了“获取键”、“根据键获取值”、“是否包含某个键或值”等等方法。

    3. Map.Entry是Map内部的一个接口,Map.Entry是一个键值对,我们要想获取Map中的Map中的键值对,可以通过Map.entrySet()来获取,获取到的是一个装着Map.Entry的集合,然后可以通过这个Entry来实现对键值的操作。

2.AbstractMap

        AbstractMap继承了Map,但没有实现entrySet()方法(该方法还是abstract修饰),如果要继承AbstractMap,需要自己实现entrySet()方法。没有真正实现put(K key, V value)方法,这里“没有真正实现”的意思是,该方法在形式上已经实现了,即没有用abstract修饰了,但是方法内部仅仅是抛出个异常,并没有真正实现方法体内容,从下面的源码中可以看到。

[java]
view plain
copy
print
?

  1. package java.util;  
  2. import java.util.Map.Entry;  
  3.   
  4. public abstract class AbstractMap<K,V> implements Map<K,V> {  
  5.     //空构造方法  
  6.     protected AbstractMap() {  
  7.     }  
  8.       
  9.     //返回Map中存储多少键值对  
  10.     public int size() {  
  11.         return entrySet().size();  
  12.     }  
  13.   
  14.     //判断Map是否为空  
  15.     public boolean isEmpty() {  
  16.         return size() == 0;  
  17.     }  
  18.       
  19.     //判断Map中是否包含值为value的键值对  
  20.     public boolean containsValue(Object value) {  
  21.     //entrySet()返回一个装有Map.Entry<K,V>的Set,然后获得Set的iterator  
  22.         Iterator<Entry<K,V>> i = entrySet().iterator();   
  23.         if (value==null) { //从这里可以看出Map中允许value==null  
  24.             while (i.hasNext()) {  
  25.                 Entry<K,V> e = i.next();  
  26.                 if (e.getValue()==null)  
  27.                     return true;  
  28.             }  
  29.         } else {  
  30.             while (i.hasNext()) {  
  31.                 Entry<K,V> e = i.next();  
  32.                 if (value.equals(e.getValue()))  
  33.                     return true;  
  34.             }  
  35.         }  
  36.         return false;  
  37.     }  
  38.       
  39.     //判断Map中是否含有键为key的键值对  
  40.     public boolean containsKey(Object key) {  
  41.         Iterator<Map.Entry<K,V>> i = entrySet().iterator();  
  42.         if (key==null) { //从这里可以看出Map中允许key==null  
  43.             while (i.hasNext()) {  
  44.                 Entry<K,V> e = i.next();  
  45.                 if (e.getKey()==null)  
  46.                     return true;  
  47.             }  
  48.         } else {  
  49.             while (i.hasNext()) {  
  50.                 Entry<K,V> e = i.next();  
  51.                 if (key.equals(e.getKey()))  
  52.                     return true;  
  53.             }  
  54.         }  
  55.         return false;  
  56.     }  
  57.       
  58.     //通过key获得对应的value值  
  59.     public V get(Object key) {  
  60.         Iterator<Entry<K,V>> i = entrySet().iterator();  
  61.         if (key==null) {   
  62.             while (i.hasNext()) {  
  63.                 Entry<K,V> e = i.next();  
  64.                 if (e.getKey()==null//从这里可以看出,key=null的必须value=null  
  65.                     return e.getValue();  
  66.             }  
  67.         } else {  
  68.             while (i.hasNext()) {  
  69.                 Entry<K,V> e = i.next();  
  70.                 if (key.equals(e.getKey()))  
  71.                     return e.getValue();  
  72.             }  
  73.         }  
  74.         return null;  
  75.     }  
  76.   
  77.     public V put(K key, V value) { //put方法体内部没有具体实现,需要继承后自己实现  
  78.         throw new UnsupportedOperationException();  
  79.     }  
  80.   
  81.     //删除指定key的Entry  
  82.     public V remove(Object key) {  
  83.         Iterator<Entry<K,V>> i = entrySet().iterator();  
  84.         Entry<K,V> correctEntry = null//用来保存待删除的Entry  
  85.         if (key==null) {  
  86.             while (correctEntry==null && i.hasNext()) {  
  87.                 Entry<K,V> e = i.next();  
  88.                 if (e.getKey()==null)  
  89.                     correctEntry = e;  
  90.             }  
  91.         } else {  
  92.             while (correctEntry==null && i.hasNext()) {  
  93.                 Entry<K,V> e = i.next();  
  94.                 if (key.equals(e.getKey()))  
  95.                     correctEntry = e;  
  96.             }  
  97.         }  
  98.   
  99.         V oldValue = null//用来保存待删除Entry的value值  
  100.         if (correctEntry !=null) { //correctEntry不为null表示找到了待删除的Entry  
  101.             oldValue = correctEntry.getValue();  
  102.             i.remove();  
  103.         }  
  104.         return oldValue;  
  105.     }  
  106.   
  107.     //向Map中添加新的Map m  
  108.     public void putAll(Map<? extends K, ? extends V> m) {  
  109.         for (Map.Entry<? extends K, ? extends V> e : m.entrySet())  
  110.             put(e.getKey(), e.getValue()); //调用上面未实现的put方法  
  111.     }  
  112.   
  113.     //清空整个Map  
  114.     public void clear() {  
  115.         entrySet().clear();  
  116.     }  
  117.   
  118.     //keySet用来保存key的Set,values用来保存value的Collection  
  119.     transient volatile Set<K>        keySet = null;  
  120.     transient volatile Collection<V> values = null;  
  121.   
  122.     //获取Map中所有的key,保存到keySet成员变量中返回。keySet是个Set<K>类型  
  123.     public Set<K> keySet() {  
  124.         if (keySet == null) {  
  125.             keySet = new AbstractSet<K>() { //内部类AbstractSet<K>  
  126.                 public Iterator<K> iterator() {  
  127.                     return new Iterator<K>() {//内部类Iterator<K>  
  128.                         private Iterator<Entry<K,V>> i = entrySet().iterator();  
  129.   
  130.                         public boolean hasNext() {  
  131.                             return i.hasNext();  
  132.                         }  
  133.   
  134.                         public K next() {  
  135.                             return i.next().getKey();  
  136.                         }  
  137.   
  138.                         public void remove() {  
  139.                             i.remove();  
  140.                         }  
  141.                     };  
  142.                 }  
  143.   
  144.                 public int size() {  
  145.                     return AbstractMap.this.size();  
  146.                 }  
  147.   
  148.                 public boolean isEmpty() {  
  149.                     return AbstractMap.this.isEmpty();  
  150.                 }  
  151.   
  152.                 public void clear() {  
  153.                     AbstractMap.this.clear();  
  154.                 }  
  155.   
  156.                 public boolean contains(Object k) {  
  157.                     return AbstractMap.this.containsKey(k);  
  158.                 }  
  159.             };  
  160.         }  
  161.         return keySet;  
  162.     }  
  163.   
  164.     //获取Map中所有的value,保存到values成员变量中返回。values是个Collection<V>类型  
  165.     public Collection<V> values() {  
  166.         if (values == null) {  
  167.             values = new AbstractCollection<V>() {  
  168.                 public Iterator<V> iterator() {  
  169.                     return new Iterator<V>() {  
  170.                         private Iterator<Entry<K,V>> i = entrySet().iterator();  
  171.   
  172.                         public boolean hasNext() {  
  173.                             return i.hasNext();  
  174.                         }  
  175.   
  176.                         public V next() {  
  177.                             return i.next().getValue();  
  178.                         }  
  179.   
  180.                         public void remove() {  
  181.                             i.remove();  
  182.                         }  
  183.                     };  
  184.                 }  
  185.   
  186.                 public int size() {  
  187.                     return AbstractMap.this.size();  
  188.                 }  
  189.   
  190.                 public boolean isEmpty() {  
  191.                     return AbstractMap.this.isEmpty();  
  192.                 }  
  193.   
  194.                 public void clear() {  
  195.                     AbstractMap.this.clear();  
  196.                 }  
  197.   
  198.                 public boolean contains(Object v) {  
  199.                     return AbstractMap.this.containsValue(v);  
  200.                 }  
  201.             };  
  202.         }  
  203.         return values;  
  204.     }  
  205.   
  206.     public abstract Set<Entry<K,V>> entrySet(); //未实现,还是抽象方法  
  207.   
  208.     //Map中的equals方法,从源码中可以看出,比较的是value的值,所有value值都相等才返回true  
  209.     public boolean equals(Object o) {  
  210.         if (o == this//如果对象都一样,必然返回true  
  211.             return true;  
  212.   
  213.         if (!(o instanceof Map)) //传进来的对象若不是Map类型肯定false  
  214.             return false;  
  215.         Map<K,V> m = (Map<K,V>) o;   
  216.         if (m.size() != size()) //两个对象的size不同肯定false  
  217.             return false;  
  218.   
  219.         try { //好了,上面的条件都满足了,下面就挨个比较value值了  
  220.             Iterator<Entry<K,V>> i = entrySet().iterator();  
  221.             while (i.hasNext()) {  
  222.                 Entry<K,V> e = i.next();  
  223.                 K key = e.getKey();  
  224.                 V value = e.getValue();  
  225.                 if (value == null) {  
  226.                     if (!(m.get(key)==null && m.containsKey(key)))  
  227.                         return false;  
  228.                 } else {  
  229.                     if (!value.equals(m.get(key)))  
  230.                         return false;  
  231.                 }  
  232.             }  
  233.         } catch (ClassCastException unused) {  
  234.             return false;  
  235.         } catch (NullPointerException unused) {  
  236.             return false;  
  237.         }  
  238.   
  239.         return true;  
  240.     }  
  241.   
  242.     //hashCode  
  243.     public int hashCode() {  
  244.         int h = 0;  
  245.         Iterator<Entry<K,V>> i = entrySet().iterator();  
  246.         while (i.hasNext())  
  247.             h += i.next().hashCode(); //调用Entry中的hashCode()方法  
  248.         return h;  
  249.     }  
  250.   
  251.     //实现toString方法:{key=value}形式输出  
  252.     public String toString() {  
  253.         Iterator<Entry<K,V>> i = entrySet().iterator();  
  254.         if (! i.hasNext())  
  255.             return “{}”;  
  256.   
  257.         StringBuilder sb = new StringBuilder(); //使用StringBuilder  
  258.         sb.append(’{‘);  
  259.         for (;;) {  
  260.             Entry<K,V> e = i.next();  
  261.             K key = e.getKey();  
  262.             V value = e.getValue();  
  263.             sb.append(key   == this ? “(this Map)” : key);  
  264.             sb.append(’=’);  
  265.             sb.append(value == this ? “(this Map)” : value);  
  266.             if (! i.hasNext())  
  267.                 return sb.append(‘}’).toString();  
  268.             sb.append(’,’).append(‘ ’);  
  269.         }  
  270.     }  
  271.   
  272.     protected Object clone() throws CloneNotSupportedException {  
  273.         AbstractMap<K,V> result = (AbstractMap<K,V>)super.clone();  
  274.         result.keySet = null;  
  275.         result.values = null;  
  276.         return result;  
  277.     }  
  278.   
  279.     private static boolean eq(Object o1, Object o2) {  
  280.         return o1 == null ? o2 == null : o1.equals(o2);  
  281.     }  
  282.   
  283.     //SimpleEntry实现了Map类中的Entry接口,另外也实现了Serializable接口,可序列化  
  284.     public static class SimpleEntry<K,V>  
  285.         implements Entry<K,V>, java.io.Serializable  
  286.     {  
  287.         private static final long serialVersionUID = -8499721149061103585L;  
  288.   
  289.         private final K key;  
  290.         private V value;  
  291.   
  292.         public SimpleEntry(K key, V value) {  
  293.             this.key   = key;  
  294.             this.value = value;  
  295.         }  
  296.   
  297.         public SimpleEntry(Entry<? extends K, ? extends V> entry) {  
  298.             this.key   = entry.getKey();  
  299.             this.value = entry.getValue();  
  300.         }  
  301.   
  302.         public K getKey() {  
  303.             return key;  
  304.         }  
  305.   
  306.         public V getValue() {  
  307.             return value;  
  308.         }  
  309.   
  310.         public V setValue(V value) {  
  311.             V oldValue = this.value;  
  312.             this.value = value;  
  313.             return oldValue;  
  314.         }  
  315.   
  316.         public boolean equals(Object o) {  
  317.             if (!(o instanceof Map.Entry))  
  318.                 return false;  
  319.             Map.Entry e = (Map.Entry)o;  
  320.             return eq(key, e.getKey()) && eq(value, e.getValue());  
  321.         }  
  322.   
  323.         public int hashCode() {  
  324.             return (key   == null ? 0 :   key.hashCode()) ^  
  325.                    (value == null ? 0 : value.hashCode());  
  326.         }  
  327.   
  328.         public String toString() {  
  329.             return key + “=” + value;  
  330.         }  
  331.   
  332.     }  
  333.   
  334.     //SimpleImmutableEntry实现了Map类中的Entry接口,另外也实现了Serializable接口,可序列化  
  335.     public static class SimpleImmutableEntry<K,V>  
  336.         implements Entry<K,V>, java.io.Serializable  
  337.     {  
  338.         private static final long serialVersionUID = 7138329143949025153L;  
  339.   
  340.         private final K key;  
  341.         private final V value;  
  342.   
  343.         public SimpleImmutableEntry(K key, V value) {  
  344.             this.key   = key;  
  345.             this.value = value;  
  346.         }  
  347.   
  348.         public SimpleImmutableEntry(Entry<? extends K, ? extends V> entry) {  
  349.             this.key   = entry.getKey();  
  350.             this.value = entry.getValue();  
  351.         }  
  352.   
  353.         public K getKey() {  
  354.             return key;  
  355.         }  
  356.   
  357.         public V getValue() {  
  358.             return value;  
  359.         }  
  360.   
  361.         public V setValue(V value) {  
  362.             throw new UnsupportedOperationException();  
  363.         }  
  364.   
  365.         public boolean equals(Object o) {  
  366.             if (!(o instanceof Map.Entry))  
  367.                 return false;  
  368.             Map.Entry e = (Map.Entry)o;  
  369.             return eq(key, e.getKey()) && eq(value, e.getValue());  
  370.         }  
  371.   
  372.         public int hashCode() {  
  373.             return (key   == null ? 0 :   key.hashCode()) ^  
  374.                    (value == null ? 0 : value.hashCode());  
  375.         }  
  376.           
  377.     //重写了toString方法,返回key=value形式  
  378.         public String toString() {  
  379.             return key + “=” + value;  
  380.         }  
  381.   
  382.     }  
  383.   
  384. }  
package java.util;
import java.util.Map.Entry;

public abstract class AbstractMap<K,V> implements Map<K,V> {
    //空构造方法
    protected AbstractMap() {
    }

    //返回Map中存储多少键值对
    public int size() {
        return entrySet().size();
    }

    //判断Map是否为空
    public boolean isEmpty() {
        return size() == 0;
    }

    //判断Map中是否包含值为value的键值对
    public boolean containsValue(Object value) {
    //entrySet()返回一个装有Map.Entry<K,V>的Set,然后获得Set的iterator
        Iterator<Entry<K,V>> i = entrySet().iterator(); 
        if (value==null) { //从这里可以看出Map中允许value==null
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                if (e.getValue()==null)
                    return true;
            }
        } else {
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                if (value.equals(e.getValue()))
                    return true;
            }
        }
        return false;
    }

    //判断Map中是否含有键为key的键值对
    public boolean containsKey(Object key) {
        Iterator<Map.Entry<K,V>> i = entrySet().iterator();
        if (key==null) { //从这里可以看出Map中允许key==null
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                if (e.getKey()==null)
                    return true;
            }
        } else {
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                if (key.equals(e.getKey()))
                    return true;
            }
        }
        return false;
    }

    //通过key获得对应的value值
    public V get(Object key) {
        Iterator<Entry<K,V>> i = entrySet().iterator();
        if (key==null) { 
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                if (e.getKey()==null) //从这里可以看出,key=null的必须value=null
                    return e.getValue();
            }
        } else {
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                if (key.equals(e.getKey()))
                    return e.getValue();
            }
        }
        return null;
    }

    public V put(K key, V value) { //put方法体内部没有具体实现,需要继承后自己实现
        throw new UnsupportedOperationException();
    }

    //删除指定key的Entry
    public V remove(Object key) {
        Iterator<Entry<K,V>> i = entrySet().iterator();
        Entry<K,V> correctEntry = null; //用来保存待删除的Entry
        if (key==null) {
            while (correctEntry==null && i.hasNext()) {
                Entry<K,V> e = i.next();
                if (e.getKey()==null)
                    correctEntry = e;
            }
        } else {
            while (correctEntry==null && i.hasNext()) {
                Entry<K,V> e = i.next();
                if (key.equals(e.getKey()))
                    correctEntry = e;
            }
        }

        V oldValue = null; //用来保存待删除Entry的value值
        if (correctEntry !=null) { //correctEntry不为null表示找到了待删除的Entry
            oldValue = correctEntry.getValue();
            i.remove();
        }
        return oldValue;
    }

    //向Map中添加新的Map m
    public void putAll(Map<? extends K, ? extends V> m) {
        for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
            put(e.getKey(), e.getValue()); //调用上面未实现的put方法
    }

    //清空整个Map
    public void clear() {
        entrySet().clear();
    }

    //keySet用来保存key的Set,values用来保存value的Collection
    transient volatile Set<K>        keySet = null;
    transient volatile Collection<V> values = null;

    //获取Map中所有的key,保存到keySet成员变量中返回。keySet是个Set<K>类型
    public Set<K> keySet() {
        if (keySet == null) {
            keySet = new AbstractSet<K>() { //内部类AbstractSet<K>
                public Iterator<K> iterator() {
                    return new Iterator<K>() {//内部类Iterator<K>
                        private Iterator<Entry<K,V>> i = entrySet().iterator();

                        public boolean hasNext() {
                            return i.hasNext();
                        }

                        public K next() {
                            return i.next().getKey();
                        }

                        public void remove() {
                            i.remove();
                        }
                    };
                }

                public int size() {
                    return AbstractMap.this.size();
                }

                public boolean isEmpty() {
                    return AbstractMap.this.isEmpty();
                }

                public void clear() {
                    AbstractMap.this.clear();
                }

                public boolean contains(Object k) {
                    return AbstractMap.this.containsKey(k);
                }
            };
        }
        return keySet;
    }

    //获取Map中所有的value,保存到values成员变量中返回。values是个Collection<V>类型
    public Collection<V> values() {
        if (values == null) {
            values = new AbstractCollection<V>() {
                public Iterator<V> iterator() {
                    return new Iterator<V>() {
                        private Iterator<Entry<K,V>> i = entrySet().iterator();

                        public boolean hasNext() {
                            return i.hasNext();
                        }

                        public V next() {
                            return i.next().getValue();
                        }

                        public void remove() {
                            i.remove();
                        }
                    };
                }

                public int size() {
                    return AbstractMap.this.size();
                }

                public boolean isEmpty() {
                    return AbstractMap.this.isEmpty();
                }

                public void clear() {
                    AbstractMap.this.clear();
                }

                public boolean contains(Object v) {
                    return AbstractMap.this.containsValue(v);
                }
            };
        }
        return values;
    }

    public abstract Set<Entry<K,V>> entrySet(); //未实现,还是抽象方法

    //Map中的equals方法,从源码中可以看出,比较的是value的值,所有value值都相等才返回true
    public boolean equals(Object o) {
        if (o == this) //如果对象都一样,必然返回true
            return true;

        if (!(o instanceof Map)) //传进来的对象若不是Map类型肯定false
            return false;
        Map<K,V> m = (Map<K,V>) o; 
        if (m.size() != size()) //两个对象的size不同肯定false
            return false;

        try { //好了,上面的条件都满足了,下面就挨个比较value值了
            Iterator<Entry<K,V>> i = entrySet().iterator();
            while (i.hasNext()) {
                Entry<K,V> e = i.next();
                K key = e.getKey();
                V value = e.getValue();
                if (value == null) {
                    if (!(m.get(key)==null && m.containsKey(key)))
                        return false;
                } else {
                    if (!value.equals(m.get(key)))
                        return false;
                }
            }
        } catch (ClassCastException unused) {
            return false;
        } catch (NullPointerException unused) {
            return false;
        }

        return true;
    }

    //hashCode
    public int hashCode() {
        int h = 0;
        Iterator<Entry<K,V>> i = entrySet().iterator();
        while (i.hasNext())
            h += i.next().hashCode(); //调用Entry中的hashCode()方法
        return h;
    }

    //实现toString方法:{key=value}形式输出
    public String toString() {
        Iterator<Entry<K,V>> i = entrySet().iterator();
        if (! i.hasNext())
            return "{}";

        StringBuilder sb = new StringBuilder(); //使用StringBuilder
        sb.append('{');
        for (;;) {
            Entry<K,V> e = i.next();
            K key = e.getKey();
            V value = e.getValue();
            sb.append(key   == this ? "(this Map)" : key);
            sb.append('=');
            sb.append(value == this ? "(this Map)" : value);
            if (! i.hasNext())
                return sb.append('}').toString();
            sb.append(',').append(' ');
        }
    }

    protected Object clone() throws CloneNotSupportedException {
        AbstractMap<K,V> result = (AbstractMap<K,V>)super.clone();
        result.keySet = null;
        result.values = null;
        return result;
    }

    private static boolean eq(Object o1, Object o2) {
        return o1 == null ? o2 == null : o1.equals(o2);
    }

    //SimpleEntry实现了Map类中的Entry接口,另外也实现了Serializable接口,可序列化
    public static class SimpleEntry<K,V>
        implements Entry<K,V>, java.io.Serializable
    {
        private static final long serialVersionUID = -8499721149061103585L;

        private final K key;
        private V value;

        public SimpleEntry(K key, V value) {
            this.key   = key;
            this.value = value;
        }

        public SimpleEntry(Entry<? extends K, ? extends V> entry) {
            this.key   = entry.getKey();
            this.value = entry.getValue();
        }

        public K getKey() {
            return key;
        }

        public V getValue() {
            return value;
        }

        public V setValue(V value) {
            V oldValue = this.value;
            this.value = value;
            return oldValue;
        }

        public boolean equals(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry e = (Map.Entry)o;
            return eq(key, e.getKey()) && eq(value, e.getValue());
        }

        public int hashCode() {
            return (key   == null ? 0 :   key.hashCode()) ^
                   (value == null ? 0 : value.hashCode());
        }

        public String toString() {
            return key + "=" + value;
        }

    }

    //SimpleImmutableEntry实现了Map类中的Entry接口,另外也实现了Serializable接口,可序列化
    public static class SimpleImmutableEntry<K,V>
        implements Entry<K,V>, java.io.Serializable
    {
        private static final long serialVersionUID = 7138329143949025153L;

        private final K key;
        private final V value;

        public SimpleImmutableEntry(K key, V value) {
            this.key   = key;
            this.value = value;
        }

        public SimpleImmutableEntry(Entry<? extends K, ? extends V> entry) {
            this.key   = entry.getKey();
            this.value = entry.getValue();
        }

        public K getKey() {
            return key;
        }

        public V getValue() {
            return value;
        }

        public V setValue(V value) {
            throw new UnsupportedOperationException();
        }

        public boolean equals(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry e = (Map.Entry)o;
            return eq(key, e.getKey()) && eq(value, e.getValue());
        }

        public int hashCode() {
            return (key   == null ? 0 :   key.hashCode()) ^
                   (value == null ? 0 : value.hashCode());
        }

    //重写了toString方法,返回key=value形式
        public String toString() {
            return key + "=" + value;
        }

    }

}

        从源码中可以看出,AbstractMap类提供了Map接口的主要实现,以最大限度地减少了实现此接口所需的工作,但是AbstractMap没有实现entrySet()方法。所以如果我们要实现不可修改的Map时,只需要扩展此类并提供entrySet()方法的实现即可,另外从源码中也可以看出,entrySet()方法返回的Set(即keySet)不支持add()或remove()方法。如果我们要实现可修改的Map,那么就必须另外重写put()方法,否则将抛出UnsupportedOperationException,而且entrySet.iterator()返回的迭代器i也必须实现其remove方法。

        不过一般我们不需要自己实现Map,因为已经有Map的实现类了,如HashMap和TreeMap等。

3.SortedMap

SortedMap也是一个接口,继承与Map接口,Sorted表示它是一个有序的键值映射。

SortedMap的排序方式有两种:自然排序和指定比较器排序。插入有序的SortedMap的所有元素都必须实现Comparable接口(或被指定的比较器所接受)。

SortedMap定义的API:

[java]
view plain
copy
print
?

  1. //继承与Map的API不再赘写  
  2. package java.util;  
  3. public interface SortedMap<K,V> extends Map<K,V> {  
  4.     Comparator<? super K> comparator(); //返回比较器对象  
  5.     SortedMap<K,V> subMap(K fromKey, K toKey); //返回指定key范围内的Map  
  6.     SortedMap<K,V> headMap(K toKey); //返回小于指定key的部分集合  
  7.     SortedMap<K,V> tailMap(K fromKey); //返回大于等于指定key的部分集合  
  8.     K firstKey(); //返回第一个元素的key  
  9.     K lastKey();  //返回最后一个元素的key  
  10. }  
//继承与Map的API不再赘写
package java.util;
public interface SortedMap<K,V> extends Map<K,V> {
    Comparator<? super K> comparator(); //返回比较器对象
    SortedMap<K,V> subMap(K fromKey, K toKey); //返回指定key范围内的Map
    SortedMap<K,V> headMap(K toKey); //返回小于指定key的部分集合
    SortedMap<K,V> tailMap(K fromKey); //返回大于等于指定key的部分集合
    K firstKey(); //返回第一个元素的key
    K lastKey();  //返回最后一个元素的key
}

4.NavigableMap

    NavigableMap继承与SortedMap,先看它的API

[java]
view plain
copy
print
?

  1. package java.util;  
  2. public interface NavigableMap<K,V> extends SortedMap<K,V> {  
  3.     Map.Entry<K,V> lowerEntry(K key);   
  4.     K lowerKey(K key);  
  5.     Map.Entry<K,V> floorEntry(K key);  
  6.     K floorKey(K key);  
  7.     Map.Entry<K,V> ceilingEntry(K key);  
  8.     K ceilingKey(K key);  
  9.     Map.Entry<K,V> higherEntry(K key);  
  10.     K higherKey(K key);  
  11.     Map.Entry<K,V> lastEntry();  
  12.     Map.Entry<K,V> pollLastEntry();  
  13.     NavigableMap<K,V> descendingMap();  
  14.     NavigableSet<K> navigableKeySet();  
  15.     NavigableSet<K> descendingKeySet();  
  16.     NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,  
  17.                              K toKey,   boolean toInclusive);  
  18.     NavigableMap<K,V> headMap(K toKey, boolean inclusive);  
  19.     NavigableMap<K,V> tailMap(K fromKey, boolean inclusive);  
  20.     SortedMap<K,V> subMap(K fromKey, K toKey);  
  21.     SortedMap<K,V> headMap(K toKey);  
  22.     SortedMap<K,V> tailMap(K fromKey);  
  23. }  
package java.util;
public interface NavigableMap<K,V> extends SortedMap<K,V> {
    Map.Entry<K,V> lowerEntry(K key); 
    K lowerKey(K key);
    Map.Entry<K,V> floorEntry(K key);
    K floorKey(K key);
    Map.Entry<K,V> ceilingEntry(K key);
    K ceilingKey(K key);
    Map.Entry<K,V> higherEntry(K key);
    K higherKey(K key);
    Map.Entry<K,V> lastEntry();
    Map.Entry<K,V> pollLastEntry();
    NavigableMap<K,V> descendingMap();
    NavigableSet<K> navigableKeySet();
    NavigableSet<K> descendingKeySet();
    NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
                             K toKey,   boolean toInclusive);
    NavigableMap<K,V> headMap(K toKey, boolean inclusive);
    NavigableMap<K,V> tailMap(K fromKey, boolean inclusive);
    SortedMap<K,V> subMap(K fromKey, K toKey);
    SortedMap<K,V> headMap(K toKey);
    SortedMap<K,V> tailMap(K fromKey);
}

    从API中我们可以看出,NavigableMap除了继承了SortedMap的特性外,还提供了如下功能:

        1. 提供了操作键值对的方法:lowerEntry、floorEntry、cellingEntry和higherEntry方法分别返回小于、小于等于、大于等于和大于给定键的键所关联的Map.Entry对象。

        2. 提供了操作键的方法:lowerKey、floorKey、cellingKey和higherKey方法分别返回小于、小于等于、大于等于和大于给定键的键。

        3. 获取键值对的子集。

5.Dictionary

    Dictionary中也包括了操作键值对的基本方法呢,它的定义以及API如下:

[java]
view plain
copy
print
?

  1. package java.util;  
  2. public abstract  
  3. class Dictionary<K,V> {  
  4.     public Dictionary() {  
  5.     }  
  6.     abstract public int size();  
  7.     abstract public boolean isEmpty();  
  8.     abstract public Enumeration<K> keys();  
  9.     abstract public Enumeration<V> elements();  
  10.     abstract public V get(Object key);  
  11.     abstract public V put(K key, V value);  
  12.     abstract public V remove(Object key);  
  13. }  
package java.util;
public abstract
class Dictionary<K,V> {
    public Dictionary() {
    }
    abstract public int size();
    abstract public boolean isEmpty();
    abstract public Enumeration<K> keys();
    abstract public Enumeration<V> elements();
    abstract public V get(Object key);
    abstract public V put(K key, V value);
    abstract public V remove(Object key);
}

        Map的架构就探讨到这吧,从下一节我们开始探讨Map接口的具体实现类。

_____________________________________________________________________________________________________________________________________________________

—–乐于分享,共同进步!

—–更多文章请看:http://blog.csdn.net/eson_15

    原文作者:java集合源码分析
    原文地址: https://blog.csdn.net/PORSCHE_GT3RS/article/details/78587751
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞