以下是Java手写HashMap的示例代码:

public class MyHashMap<K, V> {
    private static final int DEFAULT_CAPACITY = 16;
    private static final float DEFAULT_LOAD_FACTOR = 0.75f;

    private Node<K, V>[] buckets;
    private int size;

    public MyHashMap() {
        this(DEFAULT_CAPACITY);
    }

    public MyHashMap(int capacity) {
        buckets = new Node[capacity];
    }

    public void put(K key, V value) {
        int index = getIndex(key);
        Node<K, V> node = buckets[index];
        while (node != null) {
            if (node.key.equals(key)) {
                node.value = value;
                return;
            }
            node = node.next;
        }
        Node<K, V> newNode = new Node<>(key, value);
        newNode.next = buckets[index];
        buckets[index] = newNode;
        size++;
        if (size > buckets.length * DEFAULT_LOAD_FACTOR) {
            resize();
        }
    }

    public V get(K key) {
        int index = getIndex(key);
        Node<K, V> node = buckets[index];
        while (node != null) {
            if (node.key.equals(key)) {
                return node.value;
            }
            node = node.next;
        }
        return null;
    }

    public void remove(K key) {
        int index = getIndex(key);
        Node<K, V> node = buckets[index];
        Node<K, V> prev = null;
        while (node != null) {
            if (node.key.equals(key)) {
                if (prev == null) {
                    buckets[index] = node.next;
                } else {
                    prev.next = node.next;
                }
                size--;
                return;
            }
            prev = node;
            node = node.next;
        }
    }

    public int size() {
        return size;
    }

    private int getIndex(K key) {
        return key == null ? 0 : Math.abs(key.hashCode() % buckets.length);
    }

    private void resize() {
        Node<K, V>[] oldBuckets = buckets;
        buckets = new Node[oldBuckets.length * 2];
        size = 0;
        for (Node<K, V> node : oldBuckets) {
            while (node != null) {
                put(node.key, node.value);
                node = node.next;
            }
        }
    }

    private static class Node<K, V> {
        K key;
        V value;
        Node<K, V> next;

        Node(K key, V value) {
            this.key = key;
            this.value = value;
        }
    }
}

此代码实现了一个简单的HashMap,其中:

  • buckets是一个存储节点的数组,每个节点包含一个键值对和一个指向下一个节点的指针。
  • size表示HashMap的大小。
  • put方法将键值对插入HashMap中。如果已经存在相同的键,则覆盖旧值。如果HashMap的负载因子超过了默认值0.75,则对数组进行调整。
  • get方法检索键对应的值。如果键不存在,则返回null。
  • remove方法删除键值对。如果键不存在,则不执行任何操作。
  • size方法返回HashMap的大小。
  • getIndex方法根据键的哈希码计算存储桶的索引。
  • resize方法对数组进行调整,以支持更多的键值对。
  • Node类表示一个存储在HashMap中的节点。每个节点包含一个键值对和一个指向下一个节点的指针。

请注意,此代码中的实现仅用于示例目的。实际的HashMap实现可能包含更多的特性和优化。

java手写hashmap

原文地址: http://www.cveoy.top/t/topic/bmiv 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录