mirror of
https://gitee.com/gaohongy/Java-Book.git
synced 2026-07-16 09:53:50 +00:00
完成Map
This commit is contained in:
+26
-1
@@ -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及其子对象)。
|
||||
>
|
||||
>
|
||||
|
||||

|
||||
|
||||
> 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接口的基本定义,通过函数名可以知道其基本的含义。
|
||||
|
||||

|
||||
|
||||
|
||||
下图是Map接口的其他实现,包括HashMap,LinkedHashMap,TreeMap。每个Map的具体实现的引用场景不太一样,大家只需要掌握HashMap和Map接口的基本使用就可以了。
|
||||
|
||||

|
||||
|
||||
@@ -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. 统计单词出现次数
|
||||
|
||||
|
||||
Reference in New Issue
Block a user