在Java中为HashMap编写put方法,可以按照以下步骤进行:
下面是一个示例代码:
import java.util.Map;
public class MyHashMap<K, V> implements Map<K, V> {
private static final int DEFAULT_CAPACITY = 16;
private Entry<K, V>[] table;
private int size;
public MyHashMap() {
table = new Entry[DEFAULT_CAPACITY];
size = 0;
}
private static class Entry<K, V> {
private final K key;
private V value;
private Entry<K, V> next;
public Entry(K key, V value, Entry<K, V> next) {
this.key = key;
this.value = value;
this.next = next;
}
}
@Override
public V put(K key, V value) {
int index = getIndex(key);
Entry<K, V> entry = table[index];
if (entry == null) {
table[index] = new Entry<>(key, value, null);
size++;
return null;
}
while (entry != null) {
if (keyEquals(entry.key, key)) {
V oldValue = entry.value;
entry.value = value;
return oldValue;
}
entry = entry.next;
}
table[index] = new Entry<>(key, value, table[index]);
size++;
return null;
}
private int getIndex(K key) {
return key == null ? 0 : key.hashCode() % table.length;
}
private boolean keyEquals(K k1, K k2) {
return k1 == null ? k2 == null : k1.equals(k2);
}
// 其他方法的实现省略...
public static void main(String[] args) {
MyHashMap<String, Integer> map = new MyHashMap<>();
map.put("key1", 1);
map.put("key2", 2);
map.put("key3", 3);
System.out.println(map.get("key1")); // 输出:1
System.out.println(map.get("key2")); // 输出:2
System.out.println(map.get("key3")); // 输出:3
}
}
这是一个简化的HashMap实现,仅用于演示put方法的编写过程。在实际应用中,还需要考虑并发安全性、扩容机制、哈希冲突解决等问题。
领取专属 10元无门槛券
手把手带您无忧上云