Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use HashMap in Java

Shulou Source: shulou.com Published: 2022-06-03 11:00:28 11月15日 Update

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

Tags: Array article method number code value interest content at the same time more friends knowledge structure editing industry information information channels channels references storage Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Redmi Huawei Apple Linux