MapHashMapMap.EntryHashMapHashTableTreeMap Map HashMap Map.Entry HashMapclass MapDemo{ public static void main(String[] args){ Map m = new HashMap(); print("put:"+m.put("01","w111")); print("put:"+m.put("01","w112")); //会返回这个键对应
- Map
- HashMap
- Map.Entry
- HashMapclass MapDemo{ public static void main(String[] args){ Map m = new HashMap(); print("put:"+m.put("01","w111")); print("put:"+m.put("01","w112")); //会返回这个键对应的原来的值并覆盖 m.put("02","w2"); m.put("03","w3"); m.put(null,"w3"); m.put("04",null); print(m.containsKey("01")); print(m.get(null)); print(m.get("04")); print(m.values()); } public static void print(Object obj){ System.out.println(obj); }}
- 它有两个重要的方法 entrySet() KeySet() 会返回Set集合
- entrySet:public Set
entrySet() - keySet:public Set keySet()
Map.Entry
- public static interface Map.Entry映射项(键-值对)。
- 可以看见Map.Entry接口有静态修饰符。从接口的概念上来讲,接口只能由抽象方法和全局常量组成,但是内部结构是不受概念限制的,正如抽象类中可以定义抽象内部类一样,在接口中也可以定义普通内部类、抽象内部类和内部接口
- Map.entrySet 方法返回映射的 collection 视图,其中的元素属于此类。获得映射项引用的唯一 方法是通过此 collection 视图的迭代器来实现。
- 举一个一对多的例子
、 Map */import java.util.*;class MapTest{ public static void main(String[] args){ Map school = new HashMap (); Map class01 = new HashMap(); Map class02 = new HashMap(); school.put("class01",class01); school.put("class02",class02); class01.put("xiaoa",01); class01.put("xiaob",02); class02.put("xiaoc",01); class02.put("xiaod",02); getClassInfo(school); } public static void getClassInfo(Map school){ // Set keySet = school.keySet(); for (Iterator it = school.keySet().iterator();it.hasNext() ; ) { Map cls = school.get(it.next()); // for(Iterator clit = cls.keySet().iterator();clit.hasNext();){ // System.out.println(cls.get(clit.next())); // } Set clsme = cls.entrySet(); for (Iterator cli = clsme.iterator();cli.hasNext() ; ) { Map.Entry me = cli.next(); System.out.println(me.getKey()+"::"+me.getValue()); } } }} HashMapclass TreeMapTest2{ public static void main(String[] args){ String str = "asdfkcv43_gergxzkzsdaa"; char[] chs = str.toCharArray(); //Character 实现了自然排序 Comparable TreeMap tm = new TreeMap(); for (int x=0;x
='a' Integer value = tm.get(chs[x]); tm.put(chs[x],value==null?1:++value); } StringBuilder sb = new StringBuilder(); Set entrySet = tm.entrySet(); for (Iterator it = entrySet.iterator();it.hasNext() ; ) { Map.Entry me= it.next(); sb.append(me.getKey()+"("+me.getValue()+")"); } System.out.println(sb); }}【文章转自韩国多IP服务器 http://www.558idc.com/krzq.html 复制请保留原URL】