• 自定义实现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;
                    }
            }
    }

    运行结果

  • 相关阅读:
    PHP-FPM详解
    Nginx与PHP交互过程 + Nginx与PHP通信的两种方式
    cgi,fast-cgi,php-cgi,php-fpm转载详解
    ( 转 ) mysql复合索引、普通索引总结
    快速搭建ELK日志分析系统
    高并发
    多线程
    关于MySQL中查询大数据量的情况下分页limit的性能优化
    电商搜索引擎的架构设计和性能优化
    MYSQL优化之碎片整理
  • 原文地址:https://www.cnblogs.com/gczmn/p/9067319.html
Copyright © 2020-2023  润新知