Java_手工实现HashMap
2021/12/14 22:18:12
本文主要是介绍Java_手工实现HashMap,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
//自定义一个HashMap public class SxtHashMap<K,V> { Node2 [] table; //位桶数组。bucket array int size; //存放键值对的个数 public SxtHashMap(){ table = new Node2[16]; //长度一般定义为2的整数次幂 } public void put(K key,V value){ Node2 newNode = new Node2(); newNode.hash = myHash(key.hashCode(),table.length); newNode.key = key; newNode.value = value; newNode.next=null; boolean keyRepeat = false; Node2 temp = table[newNode.hash]; Node2 iterLast = null;//存放正在遍历的元素 if(temp == null){ //元素数组为空,直接将新节点放进去 table[newNode.hash] = newNode; size++; }else { //此处元素不为空,则遍历链表 while (temp !=null){ //判断key,如果重复,则覆盖 if(temp.key.equals(key)){ temp.value = value; keyRepeat = true; break; }else { //不重复,则temp=temp.next(遍历下一个) iterLast = temp; temp = temp.next; } } if (!keyRepeat){//如果没有发生重复,则添加到链表最后 iterLast.next = newNode; size++; } } } public V get(K key){ int hash = myHash(key.hashCode(),table.length); V value = null; if(table[hash]!=null){ Node2 temp = table[hash]; while (temp!=null){ if(key.equals(temp.key)){ value = (V) temp.value; break; }else { temp = temp.next; } } } return value; } public int myHash(int v, int length){ return v&(length-1); } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder("{"); for (int i = 0; i < table.length; i++) { Node2 temp = table[i]; while (temp!=null){ stringBuilder.append("["+temp.key+":"+temp.value+"]"+","); temp = temp.next; } } stringBuilder.setCharAt(stringBuilder.length()-1,'}'); return stringBuilder.toString(); } public static void main(String[] args) { SxtHashMap <Integer,String>m = new SxtHashMap<>(); m.put(1,"a"); m.put(2,"b"); m.put(3,"c"); m.put(3,"123"); for (int i = 0; i < 40; i++) { m.put(i,Character.toString((char) ('a'+i))); } m.put(23,"123"); System.out.println(m); System.out.println(m.get(1)); } }
//用于SxtHashMap public class Node2 <K,V>{ int hash; K key; V value; Node2 next; }
这篇关于Java_手工实现HashMap的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?
- 2024-05-09这种运行结果里的10.100000001,怎么能最快改成10.1?