自定义实现HashMap的put、get方法

 

public class HashMap{
        public static void main(String[] args){
            put("aa", "wo ai ni");
                System.out.println(get("aa"));
            
        }
        //首先定义一个Object类型的数组,用来存数据
        private static Object[] map = new Object[2000];
        //定义put方法
        public static void put(String key,Object object){
            //根据key计算hashcode
            int index = hashcode(key);
            //将key,value封装成对象, 方便存入数组
            Entry entry = new Entry(key, object);
            //判断hashcode值所在的节点是否有值
            if(map[index]==null){
                //如果为空,将entry添加到LinkedList中
                LinkedList link = new LinkedList<Entry>();
                link.add(entry);
                //保存LinkedList对象
                map[index] = link;
            }else{
                //如果不为null, 先获取节点上的链表,然后在链表后面添加entry对象
                LinkedList<Entry> linkedList  = (LinkedList<Entry>)map[index];
                linkedList.add(entry);
                map[index] = linkedList;
            }
        }
        //根据key获取value
        public static Object get(String key){
            int index = hashcode(key);
            //获取key对应的hashcode, 判断该节点是否为null,不为空先获取链表对象,然后遍历判断key, 返回key对应的value, 如果为null,返回null
            if(map[index]!=null){
                LinkedList<Entry> linkedList = (LinkedList<Entry>)map[index];
                for(Entry entry : linkedList){
                    if(key.equals(entry.key)){
                        return entry.value;
                    }
                }
            }
            return null;
        }
        //hashcode生成方法,不为0的字符串,转成char数组,将所有char对应的ASCII码相加, 在乘以一个数, 作为这个key对应的hashcode
        public static int hashcode(String str){
            int sum = 0;
                if(str.length() == 0){
                    return 0;               
                }else{
                     char[] ch = str.toCharArray();
                     for(char c : ch){
                        sum += (int)c;
                     }
                     sum *=3;
                     return sum;
                }
        }
}

运行结果

 

posted @ 2018-05-21 15:14  弓长张&木子李  阅读(1173)  评论(0编辑  收藏  举报