使用ArrayList实现hashmap
import java.util.ArrayList;
public class HashMap<K, V> {
private ArrayList<Pair<K, V>>[] buckets;
private int size;
public HashMap(int capacity) {
this.buckets = new ArrayList[capacity];
this.size = 0;
}
public HashMap() {
this(16);
}
public int size() {
return this.size;
}
public boolean isEmpty() {
return this.size == 0;
}
public V get(K key) {
int index = getIndex(key);
ArrayList<Pair<K, V>> bucket = buckets[index];
if (bucket == null) {
return null;
}
for (Pair<K, V> pair : bucket) {
if (pair.getKey().equals(key)) {
return pair.getValue();
}
}
return null;
}
public void put(K key, V value) {
int index = getIndex(key);
if (buckets[index] == null) {
buckets[index] = new ArrayList<>();
}
for (Pair<K, V> pair : buckets[index]) {
if (pair.getKey().equals(key)) {
pair.setValue(value);
return;
}
}
buckets[index].add(new Pair<>(key, value));
size++;
}
public V remove(K key) {
int index = getIndex(key);
ArrayList<Pair<K, V>> bucket = buckets[index];
if (bucket == null) {
return null;
}
for (Pair<K, V> pair : bucket) {
if (pair.getKey().equals(key)) {
V value = pair.getValue();
bucket.remove(pair);
size--;
return value;
}
}
return null;
}
private int getIndex(K key) {
int hash = key.hashCode();
return Math.abs(hash) % buckets.length;
}
private static class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public void setKey(K key) {
this.key = key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
}
}
加入知识星球:曹操交流(或·直达星球:https://t.zsxq.com/0canxvOCG) ,一起共勉