MyHashMap

接着前面介绍的map,实现一个基于模运算取余的最简单的HashMap

public class MyHashMap implements MyMap {
    private static final int DEFAULT_CAPACITY = 16;
    private static final float LOAD_FACTOR = 0.75f;
    private int size = 0;
    private Object[] table = new Object[DEFAULT_CAPACITY];

    @Override
    public void put(K key, V value) {
        // 检查是否需要扩容
        if (size >= table.length * LOAD_FACTOR) {
            resize(table.length * 2);
        }
        int index = getIndex(key);
        table[index] = value;
        size++;
    }

    @Override
    public V get(K key) {
        int index = getIndex(key);
        return (V) table[index];
    }

    @Override
    public boolean remove(K key) {
        if (key == null) {
            return false;
        } else {
            int index = getIndex(key);
            if (table[index] != null) {
                table[index] = null;
                size--;
                return true;
            } else {
                return false;
            }
        }
    }

    @Override
    public boolean containsKey(K key) {
        int index = getIndex(key);
        return table[index] != null;
    }

    private int getIndex(K key) {
        int hashCode = key.hashCode();
        return Math.abs(hashCode) % table.length; // 使用绝对值避免负索引
    }

    @SuppressWarnings("unchecked")
    private void resize(int newCapacity) {
        Object[] newTable = new Object[newCapacity];
        // 重新哈希所有现有元素
        for (Object value : table) {
            if (value != null) {
                K key = (K) value; // 假定值类型为键类型(仅适用于简单场景)
                int newIndex = getIndex(key);
                newTable[newIndex] = value;
            }
        }
        table = newTable;
    }
}

测试:

public class Test {
    public static void main(String[] args) {
        MyMap map = new MyHashMap<>();
        map.put("a", 1);
        map.put("b", 2);
        map.put("c", 3);
        System.out.println(map.get("a"));
        System.out.println(map.get("b"));
        map.put("a", 4);
        System.out.println(map.get("a"));
        System.out.println(map.remove("a"));
        System.out.println(map.get("a"));
        System.out.println(map.containsKey("a"));
        System.out.println(map.containsKey("b"));
    }
}

结果:

1
2
4
true
null
false
true

你可能感兴趣的:(Java数据结构,java,数据结构)