107-109_容器_自己实现HashMap_Map底层实现_哈希算法实现_使用数组和链表

package com.zhushen.map;

import java.util.LinkedList;

/**
 * 自定义Map的升级版
 * 1.提高查询效率
 * 2.HashMap的底层实现是数组+链表(链表数组)
 * @author zhushen
 *
 */
public class MyHashMap {
class  Entry {
    Object key;
    Object value;

    public Entry(Object key, Object value) {
        super();
        this.key = key;
        this.value = value;
    }   
}

    @SuppressWarnings("unchecked")
    LinkedList  arr[]  = new LinkedList[999];//HashMap的底层结构:数组+链表

    int size;
    public void put(Object key,Object value){
        Entry e=new Entry(key, value);
        int hash=key.hashCode();
        hash=hash<0?-hash:hash;
        int temp=key.hashCode()%999;
        if(arr[temp]==null){
            LinkedList list=new LinkedList();
            arr[temp]=list;
            list.add(e);
        }else{
            for(int i=0;iget(i);              
                if(e2.key.equals(key)){
                    e2.value=value; //键值重复直接覆盖
                }
            }
            arr[temp].add(e);
        }
    }
    public Object get(Object key){
        //return arr[key.hashCode()%999];
        int temp=key.hashCode()%999;
        if(arr[temp]!=null){
            for(int i=0;iget(i);               
                if(e.key.equals(key)){
                    return e.value;
                }
            }
        }
        return null;    
    }
    public static void main(String[] args) {
        MyHashMap m = new MyHashMap();
        m.put("高琪", new Wife("杨幂"));
        m.put("高琪", new Wife("李四"));
        Wife w = (Wife) m.get("高琪");
        System.out.println(w.name); 
    }
} 
  

                            
                        
                    
                    
                    

你可能感兴趣的:(Java基础,hashmap,链表,map底层结构)