JAVA-Map接口:HashMap的使用


Map:存入键值对,同时要保证键的唯一性.
<wbr>|--HashMap:<br><wbr>|--HashTable:<br><wbr>|--TreeMap:<br> Map集合取出元素的原理:<br><wbr>先将Map转成Set集合,然后对Set集合进行迭代.<br><wbr>keySet:将所有的键取出放在Set集合中,在根据Set集合得到的key值取出value值.<br><wbr>entrySet:将键值的关系取出存入Set集合,监制关系有自己的类型,为Map接口中定<br><wbr><wbr><wbr> 义的静态接口Map.Entry.可以通过getKey(),getValue()方法取值,<br></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr>

import java.util.*;
class HashMapDemo
{
<wbr>public static void main(String[] args)<br><wbr>{<br><wbr><wbr>HashMap&lt;String,String&gt; hm = new HashMap&lt;String,String&gt;();<br><wbr><wbr>//hm.put("zhansan", "chengdu1");<wbr> //不能存相同元素,取值以最后出现的元素为准.<br><wbr><wbr>hm.put("zhansan", "chengdu");<br><wbr><wbr>hm.put("lisi", "beijing");<br><wbr><wbr>hm.put("wangwu", "chongqing");<br><wbr><wbr>hm.put("zhaoliu", "jiangsu");</wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr>

<wbr><wbr>System.out.println(hm.size());</wbr></wbr>

<wbr><wbr>System.out.println("******keySet******");<br><wbr><wbr>//取出元素的第一种方式;keySet()<br><wbr><wbr>Set &lt;String&gt; st = hm.keySet();<br><wbr><wbr><br><wbr><wbr>for (Iterator&lt;String&gt; it = st.iterator(); it.hasNext(); )<br><wbr><wbr>{<br><wbr><wbr><wbr>String key = it.next();<br><wbr><wbr><wbr>String value = hm.get(key);<br><wbr><wbr><wbr>System.out.println(key+":"+value);<br><wbr><wbr>}<br><wbr><wbr>System.out.println("******entrySet******");<br><wbr><wbr>//取出元素的第二种方式;entrySet().<br><wbr><wbr>Set &lt;Map.Entry &lt;String, String&gt;&gt; entrySet = hm.entrySet();</wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr>

<wbr><wbr>for (Iterator &lt;Map.Entry &lt;String, String&gt;&gt; it = entrySet.iterator(); it.hasNext(); )<br><wbr><wbr>{<br><wbr><wbr><wbr>Map.Entry&lt;String, String&gt; me = it.next();<br><wbr><wbr><wbr>String s = me.getKey();<br><wbr><wbr><wbr>String v = me.getValue();<br><wbr><wbr><wbr>System.out.println(s+":"+v);<br><wbr><wbr>}</wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr>

<wbr><wbr>System.out.println("******entrySet******");<br><wbr><wbr>//不常用的values方法取值.<br><wbr><wbr>Collection &lt;String&gt; cl = hm.values();<br><wbr><wbr>for (Iterator&lt;String&gt; it = cl.iterator(); it.hasNext(); )<br><wbr><wbr>{<br><wbr><wbr><wbr>System.out.println(it.next());<br><wbr><wbr>}<br><wbr>}<br> }<br></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr>

你可能感兴趣的:(HashMap)