Java 手动实现HashMap

public class Node<K, V> {
	int hash;
	K key;
	V value;
	Node<K, V> next;
}
public class WhHashMap<K, V> {
	Node<K, V>[] table; // 位桶数组
	int size;

	@SuppressWarnings("unchecked")
	public WhHashMap() {
		table = new Node[16];
	}

	public void put(K key, V value) {
		Node<K, V> newNode = new Node<K, V>();
		newNode.hash = myHash(key.hashCode(), table.length);
		newNode.key = key;
		newNode.value = value;
		newNode.next = null;

		Node<K, V> temp = table[newNode.hash];
		Node<K, V> last = null;
		boolean keyRepeat = false;
		if (temp == null) {
			table[newNode.hash] = newNode; // 第一个位桶元素为空时,新节点直接放入
			size++;
		} else {
			// 遍历链表:如果重复,则覆盖,如果不重复,则追加到链表尾部
			while (temp != null) {
				// 如果重复,则覆盖值
				if (temp.key.equals(key)) {
					keyRepeat = true;
					temp.value = value;
					break;
				} else {
					// 如果不重复,则追加到链表尾部
					last = temp;
					temp = temp.next;
				}
			}
			if (!keyRepeat) { // 如果key不重复,则添加到链表最后
				last.next = newNode;
				size++;
			} else {
			}
		}

	}

	public int myHash(int v, int length) {
		// System.out.println("put-hash:" + (v & (length - 1)));
		return v & (length - 1);
	}

	// 增加get方法
	@SuppressWarnings("unchecked")
	public V get(K key) {
		int hash = myHash(key.hashCode(), table.length);
		V value = null;

		if (table[hash] != null) {
			Node<?, ?> temp = table[hash];
			while (temp != null) {
				if (temp.key.equals(key)) {
					value = (V)temp.value;
					break;
				} else {
					temp = temp.next;
				}
			}
		}
		return value;
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder("{");
		// 遍历数组
		for (int i = 0; i < table.length; i++) {
			// 遍历链表
			Node<K, V> temp = table[i];
			// TODO
			while (temp != null) {
				sb.append(temp.key + ":" + temp.value + ",");
				temp = temp.next;
			}
		}
		sb.setCharAt(sb.length() - 1, '}');
		return sb.toString();
	}

	public static void main(String[] args) {
		WhHashMap<Integer, String> map = new WhHashMap<Integer, String>();
		map.put(10, "aa"); // 10
		map.put(20, "bb"); // 4
		map.put(30, "cc"); // 14
		map.put(10, "AA"); // 10
		map.put(4, "yyy"); // 4
		map.put(36, "7777"); // 4

		System.out.println(map.toString());
		System.out.println("map size:" + map.size);

		System.out.println(map.get(10));
		System.out.println(map.get(1));
		System.out.println(map.get(36));
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
LFU(Least Frequently Used)是一种缓存淘汰算法,可以用于对缓存中的数据进行淘汰。下面是 Java 手动实现 LFU 的示例代码: ``` import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; public class LFUCache<K, V> { private Map<K, V> cacheMap; // 存放缓存数据 private Map<K, Integer> freqMap; // 存放缓存数据的访问频率 private Map<Integer, LinkedHashSet<K>> freqKeysMap; // 存放访问频率相同的缓存数据 private int capacity; // 缓存容量 private int minFreq; // 缓存数据的最小访问频率 public LFUCache(int capacity) { this.cacheMap = new HashMap<>(); this.freqMap = new HashMap<>(); this.freqKeysMap = new HashMap<>(); this.capacity = capacity; this.minFreq = 0; } public V get(K key) { V value = cacheMap.get(key); if (value == null) { return null; } // 更新缓存数据的访问频率 int freq = freqMap.get(key) + 1; freqMap.put(key, freq); // 更新访问频率相同的缓存数据 freqKeysMap.get(freq - 1).remove(key); if (freqKeysMap.get(freq - 1).isEmpty()) { freqKeysMap.remove(freq - 1); if (minFreq == freq - 1) { minFreq++; } } freqKeysMap.computeIfAbsent(freq, k -> new LinkedHashSet<>()).add(key); return value; } public void put(K key, V value) { if (capacity <= 0) { return; } // 缓存数据已存在,更新其值和访问频率 if (cacheMap.containsKey(key)) { cacheMap.put(key, value); get(key); return; } // 缓存容量已满,淘汰访问频率最小的缓存数据 if (cacheMap.size() >= capacity) { K minFreqKey = freqKeysMap.get(minFreq).iterator().next(); freqKeysMap.get(minFreq).remove(minFreqKey); if (freqKeysMap.get(minFreq).isEmpty()) { freqKeysMap.remove(minFreq); } cacheMap.remove(minFreqKey); freqMap.remove(minFreqKey); } // 添加新的缓存数据 cacheMap.put(key, value); freqMap.put(key, 1); freqKeysMap.computeIfAbsent(1, k -> new LinkedHashSet<>()).add(key); minFreq = 1; } } ``` 这个示例代码中,LFUCache 类实现了 LFU 缓存淘汰算法。在 get 方法中,缓存数据的访问频率会加 1,同时更新访问频率相同的缓存数据;在 put 方法中,如果缓存容量已满,则会淘汰访问频率最小的缓存数据,然后添加新的缓存数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值