From 16a47bc1dd225dcc6b0e95e0e0f4685dcec2c3b5 Mon Sep 17 00:00:00 2001 From: Danny <12793148@qq.com> Date: Wed, 5 Apr 2023 22:22:12 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E6=88=90Map?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 06:集合框架/02.md | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/06:集合框架/02.md b/06:集合框架/02.md index 46a7679..66d2928 100644 --- a/06:集合框架/02.md +++ b/06:集合框架/02.md @@ -108,11 +108,15 @@ public class CountKeywords { > The Map interface maps keys to the elements. The keys are like indexes. In List, the indexes are integer. In Map, the keys can be any objects. > +> Map 接口中,每个元素都是一个key-value的映射。Key如同是索引,在数组中索引是整形(integer),在Map中,Key可以是任何的引用类型(Object及其子对象)。 +> > ![image-20230402203448937](img/image-20230402203448937.png) > An instance of Map represents a group of objects, each of which is associated with a key. You can get the object from a map using a key, and you have to use a key to put the object into the map. +> +> 每一个Map的实例都代表一系列的对象组,每组中有个Key。你可以通过Key值获取一个Value,当添加的时候,必须使用key-value的形式。 @@ -122,9 +126,11 @@ public class CountKeywords { ![map](img/map.jpeg) -![image-20230402203619454](img/image-20230402203619454.png) +下图是Map接口的基本定义,通过函数名可以知道其基本的含义。 +![image-20230402203619454](img/image-20230402203619454.png) +下图是Map接口的其他实现,包括HashMap,LinkedHashMap,TreeMap。每个Map的具体实现的引用场景不太一样,大家只需要掌握HashMap和Map接口的基本使用就可以了。 ![image-20230402203630858](img/image-20230402203630858.png) @@ -143,6 +149,7 @@ public class TestMap { hashMap.put("Anderson", 31); hashMap.put("Lewis", 29); hashMap.put("Cook", 29); + hashMap.put("Cook", 31); // 修改 Cooke 的值为 31,以前Cooke为29的被改写了 System.out.println("Display entries in HashMap"); System.out.println(hashMap + "\n"); @@ -169,7 +176,25 @@ public class TestMap { } ``` +输入结果是: + +```java +Display entries in HashMap +{Lewis=29, Smith=30, Cook=31, Anderson=31} + +Display entries in ascending order of key +{Anderson=31, Cook=31, Lewis=29, Smith=30} + +The age for Lewis is 29 +Display entries in LinkedHashMap +{Smith=30, Anderson=31, Cook=29, Lewis=29} +``` + +这里一共3个Map的实现,HashMap、TreeMap和LinkedHashMap,基本使用都一样。 + +`HashMap()` +Map的put方法是向Map中增加一个Key-Value的值,第一个参数是Key,第二个参数是Value。 ### 2.2. 统计单词出现次数