HashMap is one of the most widely used implementation of Map to store key-value pairs. It was introduced in Java 1.2 and it’s an important class of Collections API. Here I am trying to implement HashMap with ArrayList.
Java中this關鍵字的用法、 HashMap是用于存儲鍵值對的Map的最廣泛使用的實現之一。 它是Java 1.2中引入的,它是Collections API的重要類。 在這里,我試圖用ArrayList實現HashMap。
The below code will provide two of the basic HashMap functions i.e get(key)
and put(key, value)
. The code also takes care of checking duplicate values while storing the entries.
Java中怎么使用數據庫? 下面的代碼將提供兩個基本的HashMap函數,即get(key)
和put(key, value)
。 該代碼還負責在存儲條目時檢查重復值。
It’s the basic implementation of HashMap and should not be used as a replacement for HashMap. Also, while testing the code, make sure that the Object used in the KEY has a proper implementation of equals() method.
java多線程代碼實現、 它是HashMap的基本實現,不應替代HashMap。 另外,在測試代碼時,請確保KEY中使用的Object具有equals()方法的正確實現。
MyHashMap.java
MyHashMap.java
package com.journaldev.util;import java.util.ArrayList;
import java.util.List;public class MyHashMap {class Container{Object key;Object value;public void insert(Object k, Object v){this.key=k;this.value=v;}}private Container c;private List<Container> recordList;public MyHashMap(){this.recordList=new ArrayList<Container>();}public void put(Object k, Object v){this.c=new Container();c.insert(k, v);//check for the same key before addingfor(int i=0; i<recordList.size(); i++){Container c1=recordList.get(i);if(c1.key.equals(k)){//remove the existing objectrecordList.remove(i);break;}}recordList.add(c);}public Object get(Object k){for(int i=0; i<this.recordList.size(); i++){Container con = recordList.get(i);//System.out.println("k.toString():"+k.toString()+"con.key.toString()"+con.key.toString());if (k.toString()==con.key.toString()) {return con.value;}}return null;}public static void main(String[] args) {MyHashMap hm = new MyHashMap();hm.put("1", "1");hm.put("2", "2");hm.put("3", "3");System.out.println(hm.get("3"));hm.put("3", "4");System.out.println(hm.get("1"));System.out.println(hm.get("3"));System.out.println(hm.get("8"));}}
The output of the above program is:
上面程序的輸出是:
3
1
4
null
Inspiration: I have been asked this question a lot in the interviews. I have also asked this question to a lot of developers in the interview. 🙂
啟示 :面試中很多人問我這個問題。 我也在面試中向很多開發人員提出了這個問題。 🙂
翻譯自: https://www.journaldev.com/146/hashmap-implementation-in-java
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态