完成Map

master
高宏宇 2 years ago
parent 9207c812c9
commit 16a47bc1dd

@ -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接口的其他实现包括HashMapLinkedHashMapTreeMap。每个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<String, Integer>()`
Map的put方法是向Map中增加一个Key-Value的值第一个参数是Key第二个参数是Value。
### 2.2. 统计单词出现次数

Loading…
Cancel
Save