zoukankan      html  css  js  c++  java
  • java.util.Dictionary源码分析

    Dictionary是一个抽象类,Hashtable是它的一个子类。

    类的声明:
    /**

    The <code>Dictionary</code> class is the abstract parent of any
    * class, such as <code>Hashtable</code>, which maps keys to values.
    * Every key and every value is an object. In any one <tt>Dictionary</tt>
    * object, every key is associated with at most one value. Given a
    * <tt>Dictionary</tt> and a key, the associated element can be looked up.
    * Any non-<code>null</code> object can be used as a key and as a value.
    * <p>
    * As a rule, the <code>equals</code> method should be used by
    * implementations of this class to decide if two keys are the same.
    * <p>
    * <strong>NOTE: This class is obsolete. New implementations should
    * implement the Map interface, rather than extending this class.</strong>

    */

    public abstract class Dictionary<K,V> 

    解释一下上面对Dictionary类的注释,Dictionary类是一个抽象的类,是Hashtable的父类,是一个key->value的映射表,任意key和value是Object,不可以是null。

    给一个Dictionary和key,它的value就能找到。equals方法用来判断两个key是否相同。特别注意,这个类已经被废弃了,不建议继续继承这个类,建议去实现Map接口。

    这个类之所以仍存在的原因是为了兼容之前使用这个类的系统。

    public Dictionary() {//使用默认的无参构造器
    }
    
    abstract public int size();//返回key的数量
    
    abstract public boolean isEmpty();//如果Dictionary不存在任何一个key-value映射,返回true,否则fasle
    
    abstract public Enumeration<K> keys();//返回包含所有key的Emumeration
    
    abstract public Enumeration<V> elements();//返回包含所有value的Emumeration
    
    abstract public V get(Object key);//根据key,查找对应的value
    
    abstract public V put(K key, V value);//插入一个key-value映射,如果key或value为nul,抛出NullPoniterException,如果已经存在相同的key,返回旧的value,如果不存                        //在相同的key,则创建一个映射到Dictionary中,返回null
    
    abstract public V remove(Object key);//根据key删除一个对应的key-value映射关系,如果Dictionary不存在这个key,相当与什么都没做,如果key是null抛出                            //NullPoniterException

    虽然Dictionary类已经被废弃了,但是研究一下它的源码还是有好处的,这样才能知道为什么会被废弃掉,以及它的替代品的优势是什么。就比如keys和elements方法返回一个Enumeration,jdk1.2之后有Iterator这个接口,可以实现遍历一个集合的对客户的透明性,以保持低耦合和单一职责原则,实现Iterator接口的迭代器类就可以实现遍历集合了,而真正的客户可以关注管理数据。

  • 相关阅读:
    模板方法模式
    备忘录模式
    观察者模式
    中介者模式
    迭代器模式
    Char型和string型字符串比较整理
    命令模式
    责任链模式
    代理模式
    dokcer 杂谈
  • 原文地址:https://www.cnblogs.com/13jhzeng/p/5559596.html
Copyright © 2011-2022 走看看