:java collections读书笔记(6) Dictionary and hashtable

这几个类,是key-value模式的,和当初的vector等依靠index获取值的方式不一样。

Properties类是比较特殊,dictionary和hashable无论key还是value,都可以是对象,而properties必须是string。

dictionary是只包含抽象方法的抽象类;据说,这个类在java引入接口前存在的,体现着类似接口的作用,在接口引入java后,这个抽象类也没有变化。

 

HASHTABLE:

无论数据结构多大,从hashtable里插入或者寻找一个数据,时间几乎是恒定的。关于这一点,hashtable是如何做到的呢?

这段话很重要:

When using the key−value pairs in a hash table, the keys are converted into an integer called a hash code by
using a hashing algorithm. This hash code is then reduced—based upon the internal storage structure used by
the hash table—to serve as an index into this structure (an array). For two equal elements, the hash code must
be the same. Two elements are defined as equal if the equals() method returns true when they are compared.
For two unequal elements, the hash code may be different or the same.

如果对于不同的element,hashcode是相同的,这就是冲突,如果造成冲突的hashcode很多,就会引起性能等的下降。

而这些相同hashcode的元素,是无法保存在一个简单的数组里的,只能存在linked list数据结构。

1)创建hashtable

   有三个构造函数:

   public Hashtable()
   public Hashtable(int initialCapacity)
   public Hashtable(int initialCapacity, float loadFactor)

   loadFactor缺省是0.75;initialCapacity缺省是11.

   如果元素数目达到Capacity*loadFactor,则,hashtable增长:2*capacity+1;

2)加入key-value

   public Object put(Object key, Object value),注意,这里的key和value都不能为null。

  public class JavaApplication1 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Hashtable myhash=new Hashtable();
        myhash.put(1,"wcf");
        myhash.put(1,"hanyu");
        myhash.put(1,"wcf");
        System.out.println(myhash.toString());
        
    }
}

则最后的值为:1,"wcf"

3)删除信息:

  public Object remove(Object key);

public void clear();

4)size

  你能控制hashtable的唯一机会,是在创建的时候指定大小。

   public int size()
public boolean isEmpty()

 如果size=0;isempty return true,else false。

操作hashtable表

 1)获取key或者value

   public Object get(Object key)

  如果没有找到,则返回null。

  public Enumeration keys()
public Set keySet()

  分别把key作为Enumeration和set返回。

  public Enumeration elements()
public Collection values()

 public Set entrySet():返回key-value对。

package javaapplication1;

import java.util.*;

/**
 *
 * @author Administrator
 */
public class JavaApplication1 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Hashtable myhash=new Hashtable();
        myhash.put(1,"wcf");
        myhash.put(2,"hanyu");
        myhash.put(3,"wcf");
      Enumeration enum1 = myhash.keys();
while (enum1.hasMoreElements()) {
Integer key = (Integer)enum1.nextElement();
System.out.println(key + " : " + myhash.get(key));
}
    }
}

run:
3 : wcf
2 : hanyu
1 : wcf
成功构建 (总时间: 0 秒)

寻找元素:

  public boolean containsKey(Object key) :注意返回值。

克隆一个hasntable:

public Object clone();

这和创建一个新hasntable,然后putall()一个效果。

 2)

原文地址:https://www.cnblogs.com/aomi/p/3138930.html