java模拟hashMap实现(linkedList方式)

package com.yys.student;

import java.util.LinkedList;

/**
 * Created by yys on 2017/5/3.
 */
public class SxtMap002 {
    LinkedList[] arr = new LinkedList[999];//数组中放链表 (此处是链表类型数组)
    int size;
    public void put(Object key,Object value){
        SxtEntry2 e = new SxtEntry2(key,value);
        int a = key.hashCode()%arr.length;
        if(arr[a] == null){
            LinkedList list = new LinkedList();
            list.add(e); //链表中存放key value
            arr[a] = list; //如果计算出的hash值在链表数组中为空 在此位置new一个链表 放在这
        }else{
            LinkedList list = arr[a]; //如果计算出的hash值在链表数组中为不为空 取出这个位置链表
            for(int i=0;i;i++){
                SxtEntry2 entry1 = (SxtEntry2)list.get(i);
                if(entry1.key.equals(key)){ //循环判断新加入元素 和以前存在于此位置的key是否相同
                    entry1.value = value; //如果相同则覆盖以前的值
                }
            }
            arr[a].add(e);//如果不相同则追加到此链表
        }
    }

    public Object get(Object key){
        int a = key.hashCode()%arr.length; //先获取hash值
        if(arr[a] != null){ //如果hash存在于数组
            LinkedList list = arr[a]; //获取hash值对应链表
            for(int i=0;i;i++){ //遍历链表
                SxtEntry2 entry2 = (SxtEntry2) list.get(i);
                if(key.equals(entry2.key)){ //链表中如果存在key相同情况
                    return entry2.value; //返回key对应value
                }
            }
        }
        return null;
    }
    public static void main(String args[]){
        SxtMap002 sxtMap = new SxtMap002();
        sxtMap.put("1",new Wife2("111"));
        sxtMap.put("1",new Wife2("222"));
        Wife2 wife = (Wife2) sxtMap.get("1");
        System.out.println(wife.getName());
    }
}

class SxtEntry2{
    Object key;
    Object value;

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

class Wife2{
    private String name;

    public Wife2(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

你可能感兴趣的:(java)