手写HashTable

首先罗列几个HashTable的方法:

1.size();

2.isEmpty();

3.clear();

4.put(String Key,Integer value);

5.get(String key);

6.containsKey(String key);

7.ContainsKey(Integer Value);

8.remove(String key);

public class HashTable{

    private ListNode[] map;

    private int size;

    private float loadFactor;

 //static final variable are global variable;

public final static int DEFAULT_CAPACITY = 16;

public final static int DEFAULT_LOAD_FACTOR = 0.75f;

  public HashTable(int capacity,float loadFactory){

      map = new ListNode(capacity);

      this.loadFactory = loadFactory;

}

  public HashTable(){

      this(DEFAULT_CAPACITY,DEFAULT_LOAD_FACTOR);

}

  public HashTable(int capacity){

      this(capacity,DEFAULT_LOAD_FACTOR);      

}

   public int size(){

      return this.size;  

}

  public void clear(){

      map = new ListNode(map.length);

      this.size = 0;

}

  private int getIndex(int hashcode){

   return hashcode % capacity;     

}

  public int getHashCode(String key){

    if(key == null){

      return 0;

}

  int hash = key.hashcode();

  if(hash < 0) 

  { hash = hash & 7FFFFFF;

    return hash;

}

}

  public void put(String key,Integer value){

      int hash = getHashCode(key);

      int index = getIndex(hash);

      ListNode node = map[index];

      if(node == null){

        node = new ListNode(key,value);

        map[index] = node;

      }

        else{

        while(node.next != null){

          if(node.key.equals(key)){

             node.value = value;

             return;

                                }

            node = node.next;

                   }

        node.next = new ListNode(key,value);

}

private boolean equalsKey(K k1, K k2){

    if(k1 == null && k2 == null){

      return true;

}

    if(k1 == null || k2 == null){

      return false;

}

    return k1.equals(k2);

}

public V put(K key, V value){

    int index = getIndex(key);

    Node<K,V> head = array[index];

    Node<K,V> node = head;

    while(node != null){

      if((equalsKey(key1,key2)){

        V result = node.value;

        node.value = value;

        return result;

}

    node = node.next;

}

}

}

  

  

  

}

原文地址:https://www.cnblogs.com/xujiangxi/p/12267129.html