Java中this關鍵字的用法,使用List在Java中的HashMap實現

 2023-11-19 阅读 26 评论 0

摘要: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是用

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。

Java中的HashMap實現 (HashMap Implementation in Java)

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

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/5/183152.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息