手写java的hashmap
时间: 2023-03-16 08:44:00 浏览: 114
我可以给你一个参考实现:public class HashMap<K, V> {
private class Node {
K key;
V value;
Node next;
}
private Node[] buckets;
private int size;
public HashMap() {
buckets = new Node[16];
size = 0;
}
public void put(K key, V value) {
int bucketIndex = getBucketIndex(key);
Node head = buckets[bucketIndex];
while (head != null) {
if (head.key.equals(key)) {
head.value = value;
return;
}
head = head.next;
}
Node newNode = new Node();
newNode.key = key;
newNode.value = value;
newNode.next = buckets[bucketIndex];
buckets[bucketIndex] = newNode;
size++;
}
public V get(K key) {
int bucketIndex = getBucketIndex(key);
Node head = buckets[bucketIndex];
while (head != null) {
if (head.key.equals(key)) {
return head.value;
}
head = head.next;
}
return null;
}
private int getBucketIndex(K key) {
int hashCode = key.hashCode();
int index = hashCode % buckets.length;
return index;
}
}
阅读全文