How to use HashMap in Java
This article mainly introduces how to use HashMap in Java, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.
The basic structure of HashMap
Package com.liuyuhe;public class Node {int hash; Object key; Object value; Node next;}
Package com.liuyuhe;public class MyHashMap {Node [] table; / / the number of key-value pairs stored in the int size; / / bucket array public MyHashMap () {table=new Node [16];}}
The put () method stores key-value pairs
Public void put (Object key,Object value) {Node newNode = newNode (); newNode.hash=myHash (key.hashCode (), table.length); newNode.key=key; newNode.value=value; newNode.next=null; Node temp= table [newNode.hash]; Node iterLast=null; if (temp==null) {table [newNode.hash] = newNode;} else {while (temptable null) {if (temp.key.equals (key)) {temp.value=value; return;} else {iterLast=temp; temp=temp.next;}} iterLast.next=newNode;} + + size } public int myHash (int v length int length) {System.out.println ("hash in myHash:" + (v & (length-1); return v & (length-1);}
Override the toString () method to print Map content
@ Override public String toString () {StringBuilder sb = new StringBuilder (); sb.append ("{"); boolean isFirst=true; / / ergodic array for (int iTuno