How to implement HashMap with separate chainning

题目
如题

答案

import java.util.Calendar;

public class MyHashMap {

    class Node {
        String key;
        int val;
        Node next;
        Node(String key, int val) { this.key = key; this.val = val;}
    }

    private Node[] array;
    final int CAPACITY = 3;

    public MyHashMap() {
        array = new Node[CAPACITY];
    }

    public Integer get(String key) {
        int hashcode = key.hashCode();
        hashcode = hashcode % CAPACITY;

        Node curr = array[hashcode];
        while(curr != null) {
            if(curr.key.equals(key)) return curr.val;
            curr = curr.next;
        }
        return null;
    }

    public void put(String key, int val) {
        int hashcode = key.hashCode();
        hashcode = hashcode % CAPACITY;

        Node curr = array[hashcode];
        if(curr == null) {
            array[hashcode] = new Node(key, val);
        }
        else {
            // Find if the key exists or not
            while(curr != null) {
                if(curr.key.equals(key)) {
                    curr.val = val;
                    return;
                }
                curr = curr.next;
            }
            // key does not exist, insert to front
            Node newnode = new Node(key, val);
            newnode.next = curr;
            array[hashcode] = newnode;
        }
    }

    public void remove(String key) {
        int hashcode = key.hashCode();
        hashcode = hashcode % CAPACITY;

        Node curr = array[hashcode];
        Node prev = null;
        while(curr != null) {
            if(curr.key.equals(key)) {
                if(prev != null) prev.next = curr.next;
                break;
            }
            prev = curr;
            curr = curr.next;
        }
    }

    public static void main(String[] args) {
        MyHashMap hashmap = new MyHashMap();

        hashmap.put("a", 2);
        System.out.println(hashmap.get("a"));

        hashmap.put("b", 5);
        System.out.println(hashmap.get("b"));

        hashmap.put("c", 7);
        System.out.println(hashmap.get("c"));

        hashmap.put("d", 8);
        System.out.println(hashmap.get("d"));

        hashmap.put("e", 9);
        System.out.println(hashmap.get("e"));

        hashmap.put("f", 10);
        System.out.println(hashmap.get("f"));
    }
}

你可能感兴趣的:(How to implement HashMap with separate chainning)