1.首先,Map是java.lang.util中定义的一个接口,而Map.Entry是Map内部的嵌套接口(既然是嵌套的,那么必然是static定义的,所以可以不用对象,直接调用)。Map接口中定义了很多方法,包括
<span style="font-size:24px;">Set<Map.Entry<key,value>> entrySet() // 返回一个Set集合,并且该集合元素是Map.Entry类型</span><pre name="code" class="java"><span style="font-size:24px;">V get(Object key) // 得到Map中的Value,返回的Value的类型</span><span style="font-size:24px;">Set keySet() //<span style="font-family: Simsun;">返回此映射中包含的键的Set</span><span style="font-family: Simsun;">视图</span></span><span style="font-family: Simsun;"><span style="font-size:24px;">Collection<V> values() //<span style="font-family: Simsun;">返回此映射中包含的值的Collection</span><span style="font-family: Simsun;">视图</span></span></span>
Map 中主要是以上四种方法能访问其元素的方法,而Map.Entry中包含有getValue()和getKey()方法,能方便的进行元素访问。
2.Map中元素访问方法
a.
<span style="font-size:24px;">Map m = new HashMap();</span><span style="font-size:24px;"><span style="white-space:pre"> </span>Iterator it = m.entrySet().iterator();</span><span style="font-size:24px;"><span style="white-space:pre"> </span>while(it.hasNext()) {</span><span style="white-space:pre"><span style="font-size:24px;"> Map.Entry entry = it.next(); //现在可以直接调用entry中的getValue()和getKey()方法。</span></span><span style="white-space:pre"><span style="font-size:24px;"><span style="white-space:pre"> </span>Oblect entry.getValue(); </span></span><span style="white-space:pre"><span style="font-size:24px;"><span style="white-space:pre"> </span>Object entry.getKey();</span></span><span style="font-size:24px;"><span style="white-space:pre"> </span>}</span>b.<span style="font-size:24px;">Map m = new HashMap();</span><span style="font-size:24px;"><span style="white-space:pre"> </span>Set kSet = map.keySet();</span><span style="font-size:24px;"><span style="white-space:pre"> </span>Iterator it = kSet.iterator();</span><span style="font-size:24px;"><span style="white-space:pre"> </span>while(it.hasNext()) {</span><span style="font-size:24px;"><span style="white-space:pre"> </span>Object key = it.next(); //先有Map中的方法keySet返回key的集合</span><span style="font-size:24px;"><span style="white-space:pre"> </span>Object value = m.get(key); //然后调用Map的get(key)方法,得到value</span><span style="font-size:24px;"><span style="white-space:pre"> </span>}</span>c.<span style="font-size:24px;">Map m = new HashMap();</span><span style="font-size:24px;"><span style="white-space:pre"> </span>Collection c = m.values();</span><span style="font-size:24px;"><span style="white-space:pre"> </span>Iterator it = c.iterator(); //直接利用Map中的value方法,遍历其中元素。</span><span style="font-size:24px;"><span style="white-space:pre"> </span>while(it.hasNext()) {</span><span style="font-size:24px;"><span style="white-space:pre"> </span>Object value = it.next();</span><span style="font-size:24px;"><span style="white-space:pre"> </span>}</span>
本文详细介绍了Java中Map接口的使用方法,包括如何通过Map.Entry进行元素访问,以及Map提供的几种不同方式来获取键值对。适用于Java初学者及需要复习Map用法的开发者。
381

被折叠的 条评论
为什么被折叠?



