手写HashMap

本文详细介绍了如何手写一个简单的HashMap,涵盖了Map接口定义、MyHashMap实现,包括初始化、Entry结构、hash函数、resize方法及get操作,并通过测试验证其功能。
摘要由CSDN通过智能技术生成

在本文中,将会实现一个简单的HashMap,模拟实现了put、get和到达扩容条件时自动扩容等功能。

    1、Map<K,V>接口的定义

public interface Map<K, V> {
	public V put(K k, V v);
	public V get(K k);
	
	public interface Entry<K, V> {
		 K getKey();
		 V getValue();
	}

	public int size();
}

    2、使用MyHashMap实现Map<K, V>接口

        2.1  MyHashMap的初始化参数

	//数组的默认初始化长度
	private static final int DEFAULT_INITAL_CAPACITY = 16;
	//默认加载因子
	private static final float DEFAULT_LOAD_FACTORY = 0.75f;

	private int initalCapacity;
	private float loadFactor;
	
	//当前map中元素的个数
	private int size = 0;
	//数组引用
	private Entry<K, V>[] table = null;
         2.2 构造方法
        public MyHashMap() {
		this(DEFAULT_INITAL_CAPACITY, DEFAULT_LOAD
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这里是一个简单的手写hashmap的实现: ```java public class MyHashMap<K, V> { private int size; private int capacity; private Node<K, V>[] table; private static class Node<K, V> { final K key; V value; Node<K, V> next; Node(K key, V value, Node<K, V> next) { this.key = key; this.value = value; this.next = next; } } public MyHashMap(int capacity) { this.size = 0; this.capacity = capacity; this.table = new Node[capacity]; } public V get(K key) { int index = hash(key); Node<K, V> node = table[index]; while (node != null) { if (node.key.equals(key)) { return node.value; } node = node.next; } return null; } public void put(K key, V value) { int index = hash(key); Node<K, V> node = table[index]; while (node != null) { if (node.key.equals(key)) { node.value = value; return; } node = node.next; } // If the key does not exist in the map, add a new node to the front of the list at the index. Node<K, V> newNode = new Node<>(key, value, table[index]); table[index] = newNode; size++; // If the map has exceeded its load factor, resize the table. if (size > capacity * 0.75) { resize(); } } public void remove(K key) { int index = hash(key); Node<K, V> node = table[index]; Node<K, V> prev = null; while (node != null) { if (node.key.equals(key)) { if (prev == null) { table[index] = node.next; } else { prev.next = node.next; } size--; return; } prev = node; node = node.next; } } private int hash(K key) { return key.hashCode() % capacity; } private void resize() { capacity *= 2; Node<K, V>[] newTable = new Node[capacity]; for (Node<K, V> node : table) { while (node != null) { Node<K, V> next = node.next; int index = hash(node.key); node.next = newTable[index]; newTable[index] = node; node = next; } } table = newTable; } } ``` 这个HashMap使用链表来解决冲突,并且在size超过capacity*0.75时会自动扩容。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值