手寫一個HashMap

package com.test.education.map;json

import com.alibaba.fastjson.JSON;app

public class MashMap<K, V> {
    // 1. 
    private static final int DEFAULT_SIZE = 1 << 4;
    private int capacity; 
    static final float loader = 0.75F;
    
    int size = 0;
    Entry<K, V>[] data = null;
    
    public MashMap() {
        this(DEFAULT_SIZE);
    }
    
    public MashMap(int innitCapacity) {
        if (innitCapacity > 0) {
            data = new Entry[innitCapacity];
            size = 0;
            this.capacity = innitCapacity;
        }
    }
    
    public int size() {
        return size;
    }
    
    public int hash (K key) {
        int h = 0;
        if (key == null) {
            h = 0;
        } else {
            h = key.hashCode() ^ (h >>> 16);
        }
        return h % capacity;
    }
    
    public void put (K key, V value) {
        if (null == key) {
            throw new RuntimeException("key is null");
        }
        
        int hash = hash(key);
        Entry<K, V> entry = new Entry<K, V>(key, value, null);
         Entry<K, V> curEntry = data[hash];
         while (null != curEntry) {
            if (curEntry.getKey().equals(key)) {
                // 若是存在就覆蓋
                curEntry.v = value;
                return;
            }
            curEntry = curEntry.next;
        }
        
         entry.next = data[hash];
        data[hash] = entry;
        size++;
    }
    
    public V getKey(K key) {
        int hash = hash(key);
        
        Entry<K, V> entry = data[hash];
        
        while (null != entry) {
            if (entry.getKey().equals(key)) {
                return entry.getValue();
            }
            entry = entry.next;
        }
        return null;
    }
    
    public String toString () {
        StringBuffer buffer = new StringBuffer("[");
        for(Entry<K, V> entry : data) {
            if (null != entry){
                buffer.append("{\"key\":\"").append(entry.getKey())
                .append("\",\"value\":\"").append(entry.getValue()).append("\"}");
                buffer.append(",");
            }
        }
        if (buffer.indexOf(",")!=-1) {
            buffer.deleteCharAt(buffer.length() - 1);
        }
        buffer.append("]");
        return buffer.toString();
    }
    
    class Entry<K, V> {
        K k;
        V v;
        Entry<K, V> next;
        
        public Entry(K k, V v, Entry<K, V> next) {
            this.k = k;
            this.v = v;
            this.next = next;
        }
        
        public String toString () {
            return "key=" + k + ";value=" + v; 
        }
        
        public K getKey(){
            return k;
        }
        
        public V getValue() {
            return v;
        }
    }
    
    
}
 this

相關文章
相關標籤/搜索