前言:
jdk8底层hashmap实现原理:
hashmap手写:
package 二叉树;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
public class HashMap<K,V> implements Map<K,V> {
private Entry<K,V>[] table=null;
private int size=0;
public HashMap(){
table=new Entry[16];
}
@Override
public int size() {
return 0;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public boolean containsKey(Object key) {
return false;
}
@Override
public boolean containsValue(Object value) {
return false;
}
@Override
public V get(Object key) {
if(size==0){
return null;
}
int index=hash((K) key);
// Entry entry=table[index];
// return (V) entry.getValue(); //没有发生hash存储位置碰撞 这样没用到链表
Entry entry = getEntry((K)key,index);
return entry==null?null:(V)entry.getValue();
}
private Entry<K,V>getEntry(K k,int index) {
for (Entry<K,V> e = table[index]; e!=null; e=e.next){
if(e.hash==index&&(k==e.getKey()||k.equals(e.getKey()))){
return e;
}
}
return null;
}
@Override
public V put(K key, V value) {
int index=hash(key);
Entry entry=table[index];
if(entry==null){
table[index]=new Entry<>(key,value,index,null);
size++;
}else {
table[index]=new Entry<>(key,value,index,entry);
}
return table[index].getValue();
}
private int hash(K k){
int index=k.hashCode()%(15);
return Math.abs(index);
}
@Override
public V remove(Object key) {
return null;
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
}
@Override
public void clear() {
}
@Override
public Set<K> keySet() {
return null;
}
@Override
public Collection<V> values() {
return null;
}
@Override
public Set<Map.Entry<K, V>> entrySet() {
return null;
}
class Entry<K,V> implements Map.Entry<K,V>{
private K k;
private V v;
int hash;
Entry<K,V> next;
public Entry(K k, V v, int hash, Entry<K, V> next) {
this.k = k;
this.v = v;
this.hash = hash;
this.next = next;
}
@Override
public K getKey() {
return k;
}
@Override
public V getValue() {
return v;
}
@Override
public V setValue(V value) {
return null;
}
}
public static void main(String[] args) {
HashMap<Object,Object> hashMap=new HashMap<>();
hashMap.put("monkey","123");
System.out.println(hashMap.get("monkey"));
}
}
//class test {
// public static void main(String[] args) {
// HashMap<Object,Object> hashMap=new HashMap<>();
// hashMap.put("monkey","123");
// System.out.println(hashMap.get("monkey"));
// }
//}