zoukankan      html  css  js  c++  java
  • 自定义实现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;
                    }
            }
    }

    运行结果

  • 相关阅读:
    在插入一条记录后 取得自动增长ID
    hashtable,dictionary 从原理上说说有什么异同,哪个性能高一些
    单例模式
    聚簇索引与非聚簇索引的区别
    基于SQL SERVER2008的SCCM2007部署
    XML架构下的表结构设置主键
    IE6与IE7下一点样式的区别
    Session丢失原因与解决方案小结
    Python_如何去除字符串里的空格
    Python_让人脑阔疼的编码问题(转)+(整理)
  • 原文地址:https://www.cnblogs.com/gczmn/p/9067319.html
Copyright © 2011-2022 走看看