forked from netkiller/netkiller.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmap.html
More file actions
311 lines (257 loc) · 14.9 KB
/
map.html
File metadata and controls
311 lines (257 loc) · 14.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>1.6. Map</title><link rel="stylesheet" type="text/css" href="/docbook.css" /><meta name="generator" content="DocBook XSL Stylesheets Vsnapshot" /><link rel="home" href="index.html" title="Netkiller Java 手札" /><link rel="up" href="java.html" title="第 1 章 Java 14" /><link rel="prev" href="Collection.html" title="1.5. Collection" /><link rel="next" href="java.util.Queue.html" title="1.7. Queue" /></head><body><a xmlns="" href="//www.netkiller.cn/">Home</a> |
<a xmlns="" href="//netkiller.github.io/">简体中文</a> |
<a xmlns="" href="http://netkiller.sourceforge.net/">繁体中文</a> |
<a xmlns="" href="/journal/index.html">杂文</a> |
<a xmlns="" href="https://zhuanlan.zhihu.com/netkiller">知乎专栏</a> |
<a xmlns="" href="https://github.com/netkiller">Github</a> |
<a xmlns="" href="http://my.oschina.net/neochen/">OSChina 博客</a> |
<a xmlns="" href="https://cloud.tencent.com/developer/column/2078">云社区</a> |
<a xmlns="" href="https://yq.aliyun.com/u/netkiller/">云栖社区</a> |
<a xmlns="" href="https://www.facebook.com/bg7nyt">Facebook</a> |
<a xmlns="" href="http://cn.linkedin.com/in/netkiller/">Linkedin</a> |
<a xmlns="" href="//www.netkiller.cn/home/video.html">视频教程</a> |
<a xmlns="" href="//www.netkiller.cn/home/donations.html">打赏(Donations)</a> |
<a xmlns="" href="//www.netkiller.cn/home/about.html">About</a><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="3" align="center">1.6. Map</th></tr><tr><td width="20%" align="left"><a accesskey="p" href="Collection.html">上一页</a> </td><th width="60%" align="center">第 1 章 Java 14</th><td width="20%" align="right"> <a accesskey="n" href="java.util.Queue.html">下一页</a></td></tr></table><hr /></div><table xmlns=""><tr><td><iframe src="//ghbtns.com/github-btn.html?user=netkiller&repo=netkiller.github.io&type=watch&count=true&size=large" height="30" width="170" frameborder="0" scrolling="0" style="width:170px; height: 30px;" allowTransparency="true"></iframe></td><td><iframe src="//ghbtns.com/github-btn.html?user=netkiller&repo=netkiller.github.io&type=fork&count=true&size=large" height="30" width="170" frameborder="0" scrolling="0" style="width:170px; height: 30px;" allowTransparency="true"></iframe></td><td><iframe src="//ghbtns.com/github-btn.html?user=netkiller&type=follow&count=true&size=large" height="30" width="240" frameborder="0" scrolling="0" style="width:240px; height: 30px;" allowTransparency="true"></iframe></td><td></td><td><a href="https://zhuanlan.zhihu.com/netkiller"><img src="/images/logo/zhihu-card-default.svg" height="25" /></a></td><td valign="middle"><a href="https://zhuanlan.zhihu.com/netkiller">知乎专栏</a> | <a href="https://www.zhihu.com/club/1241768772601950208">多维度架构</a></td><td> | </td><td>微信号 netkiller-ebook </td><td> | </td><td>QQ群:128659835 请注明“读者”</td></tr></table><div class="section"><div class="titlepage"><div><div><h2 class="title" style="clear: both"><a id="map"></a>1.6. Map</h2></div></div></div>
<pre class="screen">
Map
├Hashtable
├HashMap
└WeakHashMap
Map接口
请注意,Map没有继承Collection接口,Map提供key到value的映射。一个Map中不能包含相同的key,每个key只能映射一个 value。Map接口提供3种集合的视图,Map的内容可以被当作一组key集合,一组value集合,或者一组key-value映射。
Hashtable类
Hashtable继承Map接口,实现一个key-value映射的哈希表。任何非空(non-null)的对象都可作为key或者value。
添加数据使用put(key, value),取出数据使用get(key),这两个基本操作的时间开销为常数。
Hashtable通过initial capacity和load factor两个参数调整性能。通常缺省的load factor 0.75较好地实现了时间和空间的均衡。增大load factor可以节省空间但相应的查找时间将增大,这会影响像get和put这样的操作。
使用Hashtable的简单示例如下,将1,2,3放到Hashtable中,他们的key分别是”one”,”two”,”three”:
Hashtable numbers = new Hashtable();
numbers.put(“one”, new Integer(1));
numbers.put(“two”, new Integer(2));
numbers.put(“three”, new Integer(3));
要取出一个数,比如2,用相应的key:
Integer n = (Integer)numbers.get(“two”);
System.out.println(“two = ” + n);
由于作为key的对象将通过计算其散列函数来确定与之对应的value的位置,因此任何作为key的对象都必须实现hashCode和equals方 法。hashCode和equals方法继承自根类Object,如果你用自定义的类当作key的话,要相当小心,按照散列函数的定义,如果两个对象相 同,即obj1.equals(obj2)=true,则它们的hashCode必须相同,但如果两个对象不同,则它们的hashCode不一定不同,如 果两个不同对象的hashCode相同,这种现象称为冲突,冲突会导致操作哈希表的时间开销增大,所以尽量定义好的hashCode()方法,能加快哈希 表的操作。
如果相同的对象有不同的hashCode,对哈希表的操作会出现意想不到的结果(期待的get方法返回null),要避免这种问题,只需要牢记一条:要同时复写equals方法和hashCode方法,而不要只写其中一个。
Hashtable是同步的。
HashMap类
HashMap和Hashtable类似,不同之处在于HashMap是非同步的,并且允许null,即null value和null key。,但是将HashMap视为Collection时(values()方法可返回Collection),其迭代子操作时间开销和HashMap 的容量成比例。因此,如果迭代操作的性能相当重要的话,不要将HashMap的初始化容量设得过高,或者load factor过低。
WeakHashMap类
WeakHashMap是一种改进的HashMap,它对key实行“弱引用”,如果一个key不再被外部所引用,那么该key可以被GC回收。
</pre>
<div class="section"><div class="titlepage"><div><div><h3 class="title"><a id="idp36"></a>1.6.1. 初始化</h3></div></div></div>
<pre class="programlisting">
Map<String, Object> data = new HashMap<String, Object>() {
{
put("name", "neo");
}
};
</pre>
</div>
<div class="section"><div class="titlepage"><div><div><h3 class="title"><a id="map.static"></a>1.6.2. static map</h3></div></div></div>
<pre class="programlisting">
private static final Map<String, String> point;
static {
point = new HashMap<String, String>();
point.put("CN", "China");
point.put("HK", "Hongkong");
point.put("TW", "Taiwan");
};
</pre>
<pre class="programlisting">
public final static Map<String, String> hostMap = new HashMap<String, String>() {
{
put("redis", "127.0.0.1");
put("solr", "127.0.0.1");
}
};
public final static Map map = new HashMap() {{
put("key1", "value1");
put("key2", "value2");
}};
</pre>
</div>
<div class="section"><div class="titlepage"><div><div><h3 class="title"><a id="hashmap"></a>1.6.3. HashMap</h3></div></div></div>
<div class="section"><div class="titlepage"><div><div><h4 class="title"><a id="idp37"></a>1.6.3.1. 遍历 HashMap</h4></div></div></div>
<pre class="programlisting">
Map<String, Integer> session = new HashMap<String, Integer>();
session.put("A",1);
...
...
session.put("Z",26)
for (Map.Entry<String, Integer> entry : session.entrySet()) {
System.out.println(String.format("%s:%d", entry.getKey(), entry.getValue()));
}
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
</pre>
</div>
<div class="section"><div class="titlepage"><div><div><h4 class="title"><a id="idp38"></a>1.6.3.2. 遍历map中的键</h4></div></div></div>
<pre class="programlisting">
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
//遍历map中的键
for (Integer key : map.keySet()) {
System.out.println("Key = " + key);
}
</pre>
</div>
<div class="section"><div class="titlepage"><div><div><h4 class="title"><a id="idp39"></a>1.6.3.3. 遍历map中的值 </h4></div></div></div>
<pre class="programlisting">
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Integer value : map.values()) {
System.out.println("Value = " + value);
}
</pre>
</div>
<div class="section"><div class="titlepage"><div><div><h4 class="title"><a id="idp40"></a>1.6.3.4. 通过键取值</h4></div></div></div>
<pre class="programlisting">
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Integer key : map.keySet()) {
Integer value = map.get(key);
System.out.println("Key = " + key + ", Value = " + value);
}
</pre>
</div>
<div class="section"><div class="titlepage"><div><div><h4 class="title"><a id="idp41"></a>1.6.3.5. 使用 Iterator 遍历 HashMap</h4></div></div></div>
<pre class="programlisting">
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<Integer, Integer> entry = entries.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
Map map = new HashMap();
Iterator entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
Integer key = (Integer)entry.getKey();
Integer value = (Integer)entry.getValue();
System.out.println("Key = " + key + ", Value = " + value);
}
</pre>
</div>
</div>
<div class="section"><div class="titlepage"><div><div><h3 class="title"><a id="LinkedHashMap"></a>1.6.4. LinkedHashMap</h3></div></div></div>
<pre class="programlisting">
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
public class TestLinkedHashMap {
public static void main(String args[])
{
System.out.println("*** LinkedHashMap ***");
Map<Integer,String> map = new LinkedHashMap<Integer,String>();
map.put(6, "apple");
map.put(3, "banana");
map.put(2,"pear");
for (Iterator it = map.keySet().iterator();it.hasNext();)
{
Object key = it.next();
System.out.println( key+"="+ map.get(key));
}
System.out.println("*** HashMap ***");
Map<Integer,String> map1 = new HashMap<Integer,String>();
map1.put(6, "apple");
map1.put(3, "banana");
map1.put(2,"pear");
for (Iterator it = map1.keySet().iterator();it.hasNext();)
{
Object key = it.next();
System.out.println( key+"="+ map1.get(key));
}
}
}
</pre>
</div>
<div class="section"><div class="titlepage"><div><div><h3 class="title"><a id="map.forEach"></a>1.6.5. Map forEach</h3></div></div></div>
<pre class="programlisting">
Map<String, Integer> items = new HashMap<>();
items.put("A", 10);
items.put("B", 20);
items.put("C", 30);
items.put("D", 40);
items.put("E", 50);
items.put("F", 60);
items.forEach((k,v)->System.out.println("key : " + k + "; value : " + v));
//output
key : A value : 10
key : B value : 20
key : C value : 30
key : D value : 40
key : E value : 50
key : F value : 60
items.forEach((k,v)->{
System.out.println("key : " + k + " value : " + v);
});
</pre>
</div>
</div><div xmlns="" id="disqus_thread"></div><script xmlns="">
var disqus_config = function () {
this.page.url = "http://www.netkiller.cn"; // Replace PAGE_URL with your page's canonical URL variable
this.page.identifier = 'netkiller'; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
};
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = '//netkiller.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script><noscript xmlns="">Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript><br xmlns="" /><script xmlns="" type="text/javascript" id="clustrmaps" src="//cdn.clustrmaps.com/map_v2.js?u=r5HG&d=9mi5r_kkDC8uxG8HuY3p4-2qgeeVypAK9vMD-2P6BYM"></script><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="Collection.html">上一页</a> </td><td width="20%" align="center"><a accesskey="u" href="java.html">上一级</a></td><td width="40%" align="right"> <a accesskey="n" href="java.util.Queue.html">下一页</a></td></tr><tr><td width="40%" align="left" valign="top">1.5. Collection </td><td width="20%" align="center"><a accesskey="h" href="index.html">起始页</a></td><td width="40%" align="right" valign="top"> 1.7. Queue</td></tr></table></div><script xmlns="">
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-11694057-1', 'auto');
ga('send', 'pageview');
</script><script xmlns="" async="async">
var _hmt = _hmt || [];
(function() {
var hm = document.createElement("script");
hm.src = "https://hm.baidu.com/hm.js?93967759a51cda79e49bf4e34d0b0f2c";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(hm, s);
})();
</script><script xmlns="" async="async">
(function(){
var bp = document.createElement('script');
var curProtocol = window.location.protocol.split(':')[0];
if (curProtocol === 'https') {
bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
}
else {
bp.src = 'http://push.zhanzhang.baidu.com/push.js';
}
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(bp, s);
})();
</script></body></html>