Map(二):AbstractMap

AbstractMap作为Map接口的骨架实现,提供了通用函数并简化了具体实现。它依赖于entrySet()返回的键值对集合视图来实现查询操作。此外,AbstractMap还提供了SimpleEntry和SimpleImmutableEntry两种Entry实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

AbstractMap是一个抽象类,它是Map接口的一个骨架实现,最小化实现了此接口提供的抽象函数。在Java的Collection框架中基本都遵循了这一规定,骨架实现在接口与实现类之间构建了一层抽象,其目的是为了复用一些比较通用的函数以及方便扩展,例如List接口拥有骨架实现AbstractList、Set接口拥有骨架实现AbstractSet等。

下面我们按照不同的操作类型来看看AbstractMap都实现了什么,首先是查询操作:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

package java.util;

import java.util.Map.Entry;

public abstract class AbstractMap<K,V> implements Map<K,V> {

 

    protected AbstractMap() {

    }

    // Query Operations

    public int size() {

        return entrySet().size();

    }

    // 键值对的集合视图留给具体的实现类实现

    public abstract Set<Entry<K,V>> entrySet();

    public boolean isEmpty() {

        return size() == 0;

    }

    /**

     * 遍历entrySet,然后逐个进行比较。

     */

    public boolean containsValue(Object value) {

        Iterator<Entry<K,V>> i = entrySet().iterator();

        if (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;

    }

    /**

     * 跟containsValue()同理,只不过比较的是key。

     */

    public boolean containsKey(Object key) {

        Iterator<Map.Entry<K,V>> i = entrySet().iterator();

        if (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;

    }

    /**

     * 遍历entrySet,然后根据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)

                    return e.getValue();

            }

        } else {

            while (i.hasNext()) {

                Entry<K,V> e = i.next();

                if (key.equals(e.getKey()))

                    return e.getValue();

            }

        }

        return null;

    }

}

可以发现这些操作都是依赖于函数entrySet()的,它返回了一个键值对的集合视图,由于不同的实现子类的Entry实现可能也是不同的,所以一般是在内部实现一个继承于AbstractSet且泛型为Map.Entry的内部类作为EntrySet,接下来是修改操作与批量操作:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

// Modification Operations

/**

 * 没有提供实现,子类必须重写该方法,否则调用put()会抛出异常。

 */

public V put(K key, V value) {

    throw new UnsupportedOperationException();

}

/**

 * 遍历entrySet,先找到目标的entry,然后删除。

 *(还记得之前说过的吗,集合视图中的操作也会影响到实际数据)

 */

public V remove(Object key) {

    Iterator<Entry<K,V>> i = entrySet().iterator();

    Entry<K,V> correctEntry = null;

    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;

    if (correctEntry !=null) {

        oldValue = correctEntry.getValue();

        i.remove();

    }

    return oldValue;

}

// Bulk Operations

/**

 * 遍历参数m,然后将每一个键值对put到该Map中。

 */

public void putAll(Map<? extends K, ? extends V> m) {

    for (Map.Entry<? extends K, ? extends V> e : m.entrySet())

        put(e.getKey(), e.getValue());

}

/**

 * 清空entrySet等价于清空该Map。

 */

public void clear() {

    entrySet().clear();

}

AbstractMap并没有实现put()函数,这样做是为了考虑到也许会有不可修改的Map实现子类继承它,而对于一个可修改的Map实现子类则必须重写put()函数。

AbstractMap没有提供entrySet()的实现,但是却提供了keySet()values()集合视图的默认实现,它们都是依赖于entrySet()返回的集合视图实现的,源码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

/**

 * keySet和values是lazy的,它们只会在第一次请求视图时进行初始化,

 * 而且它们是无状态的,所以只需要一个实例(初始化一次)。

 */

transient Set<K>        keySet;

transient Collection<V> values;

/**

 * 返回一个AbstractSet的子类,可以发现它的行为都委托给了entrySet返回的集合视图

 * 与当前的AbstractMap实例,所以说它自身是无状态的。

 */

public Set<K> keySet() {

    Set<K> ks = keySet;

    if (ks == null) {

        ks = new AbstractSet<K>() {

            public Iterator<K> iterator() {

                return new 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);

            }

        };

        keySet = ks;

    }

    return ks;

}

/**

 * 与keySet()基本一致,唯一的区别就是返回的是AbstractCollection的子类,

 * 主要是因为value不需要保持互异性。

 */

public Collection<V> values() {

    Collection<V> vals = values;

    if (vals == null) {

        vals = 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);

            }

        };

        values = vals;

    }

    return vals;

}

它还提供了两个Entry的实现类:SimpleEntry与SimpleImmutableEntry,这两个类的实现非常简单,区别也只是前者是可变的,而后者是不可变的。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

private static boolean eq(Object o1, Object o2) {

    return o1 == null ? o2 == null : o1.equals(o2);

}

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;

    }

}

/**

 * 它与SimpleEntry的区别在于它是不可变的,value被final修饰,并且不支持setValue()。

 */

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());

    }

    public String toString() {

        return key + "=" + value;

    }

}

我们通过阅读上述的源码不难发现,AbstractMap实现的操作都依赖于entrySet()所返回的集合视图。剩下的函数就没什么好说的了,有兴趣的话可以自己去看看。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值