给出java实现hashmap的详细代码
时间: 2023-03-31 21:01:52 浏览: 76
可以的,以下是Java实现HashMap的详细代码:
```
import java.util.ArrayList;
import java.util.List;
public class MyHashMap<K, V> {
private static final int DEFAULT_CAPACITY = 16;
private static final float DEFAULT_LOAD_FACTOR = .75f;
private int capacity;
private float loadFactor;
private int size;
private List<Node<K, V>>[] buckets;
public MyHashMap() {
this(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR);
}
public MyHashMap(int capacity, float loadFactor) {
this.capacity = capacity;
this.loadFactor = loadFactor;
this.size = ;
this.buckets = new ArrayList[capacity];
}
public void put(K key, V value) {
int index = getIndex(key);
List<Node<K, V>> bucket = getBucket(index);
for (Node<K, V> node : bucket) {
if (node.key.equals(key)) {
node.value = value;
return;
}
}
bucket.add(new Node<>(key, value));
size++;
if (size > capacity * loadFactor) {
resize();
}
}
public V get(K key) {
int index = getIndex(key);
List<Node<K, V>> bucket = getBucket(index);
for (Node<K, V> node : bucket) {
if (node.key.equals(key)) {
return node.value;
}
}
return null;
}
public void remove(K key) {
int index = getIndex(key);
List<Node<K, V>> bucket = getBucket(index);
for (Node<K, V> node : bucket) {
if (node.key.equals(key)) {
bucket.remove(node);
size--;
return;
}
}
}
public int size() {
return size;
}
private int getIndex(K key) {
return key.hashCode() % capacity;
}
private List<Node<K, V>> getBucket(int index) {
if (buckets[index] == null) {
buckets[index] = new ArrayList<>();
}
return buckets[index];
}
private void resize() {
capacity *= 2;
List<Node<K, V>>[] newBuckets = new ArrayList[capacity];
for (List<Node<K, V>> bucket : buckets) {
if (bucket != null) {
for (Node<K, V> node : bucket) {
int index = getIndex(node.key);
List<Node<K, V>> newBucket = getBucket(index, newBuckets);
newBucket.add(node);
}
}
}
buckets = newBuckets;
}
private List<Node<K, V>> getBucket(int index, List<Node<K, V>>[] buckets) {
if (buckets[index] == null) {
buckets[index] = new ArrayList<>();
}
return buckets[index];
}
private static class Node<K, V> {
K key;
V value;
Node(K key, V value) {
this.key = key;
this.value = value;
}
}
}
```