hashmap原理面试回答
时间: 2023-12-12 08:36:05 浏览: 26
HashMap是一种散列表,它存储的内容是键值对(key-value)映射。当我们将一个键值对存储在HashMap中时,它会根据键的哈希码找到对应的桶(bucket),然后将键值对存储在桶中。当我们需要获取一个键对应的值时,HashMap会根据键的哈希码找到对应的桶,然后在桶中查找对应的值。
在面试中,如果被问到HashMap是否有序,我们需要回答说HashMap不是有序的,因为HashMap中的键值对是根据哈希码存储的,而哈希码是无序的。如果被问到HashMap的存储原理,我们需要回答说HashMap是通过哈希算法将键映射到桶中的,然后将键值对存储在桶中。如果被问到哈希算法的底层实现,我们需要回答说哈希算法的底层实现是哈希表。
以下是一个简单的HashMap的实现代码,仅供参考:
```java
public class MyHashMap<K, V> {
private static final int DEFAULT_CAPACITY = 16;
private static final float DEFAULT_LOAD_FACTOR = 0.75f;
private Entry<K, V>[] table;
private int size;
private int capacity;
private float loadFactor;
public MyHashMap() {
this(DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR);
}
public MyHashMap(int capacity, float loadFactor) {
this.capacity = capacity;
this.loadFactor = loadFactor;
this.table = new Entry[capacity];
}
public void put(K key, V value) {
int index = hash(key);
Entry<K, V> entry = table[index];
while (entry != null) {
if (entry.key.equals(key)) {
entry.value = value;
return;
}
entry = entry.next;
}
Entry<K, V> newEntry = new Entry<>(key, value);
newEntry.next = table[index];
table[index] = newEntry;
size++;
if (size > capacity * loadFactor) {
resize();
}
}
public V get(K key) {
int index = hash(key);
Entry<K, V> entry = table[index];
while (entry != null) {
if (entry.key.equals(key)) {
return entry.value;
}
entry = entry.next;
}
return null;
}
private int hash(K key) {
return key.hashCode() % capacity;
}
private void resize() {
capacity *= 2;
Entry<K, V>[] newTable = new Entry[capacity];
for (Entry<K, V> entry : table) {
while (entry != null) {
Entry<K, V> next = entry.next;
int index = hash(entry.key);
entry.next = newTable[index];
newTable[index] = entry;
entry = next;
}
}
table = newTable;
}
private static class Entry<K, V> {
K key;
V value;
Entry<K, V> next;
public Entry(K key, V value) {
this.key = key;
this.value = value;
}
}
}
```