复制代码
- //:Map1.java
- //ThingsyoucandowithMaps
- packagec08.newcollections;
- importjava.util.*;
- publicclassMap1{
- publicfinalstaticString[][]testData1={
- {"Happy","Cheerfuldisposition"},
- {"Sleepy","Prefersdark,quietplaces"},
- {"Grumpy","Needstoworkonattitude"},
- {"Doc","Fantasizesaboutadvanceddegree"},
- {"Dopey","Aforeffort"},
- {"Sneezy","Struggleswithallergies"},
- {"Bashful","Needsself-esteemworkshop"},
- };
- publicfinalstaticString[][]testData2={
- {"Belligerent","Disruptiveinfluence"},
- {"Lazy","Motivationalproblems"},
- {"Comatose","Excellentbehavior"}
- };
- publicstaticMapfill(Mapm,Object[][]o){
- for(inti=0;i<o.length;i++)
- m.put(o[i][0],o[i][1]);
- returnm;
- }
- //ProducingaSetofthekeys:
- publicstaticvoidprintKeys(Mapm){
- System.out.print("Size="+m.size()+",");
- System.out.print("Keys:");
- Collection1.print(m.keySet());
- }
- //ProducingaCollectionofthevalues:
- publicstaticvoidprintValues(Mapm){
- System.out.print("Values:");
- Collection1.print(m.values());
- }
- //IteratingthroughMap.Entryobjects(pairs):
- publicstaticvoidprint(Mapm){
- Collectionentries=m.entries();
- Iteratorit=entries.iterator();
- while(it.hasNext()){
- Map.Entrye=(Map.Entry)it.next();
- System.out.println("Key="+e.getKey()+
- ",Value="+e.getValue());
- }
- }
- publicstaticvoidtest(Mapm){
- fill(m,testData1);
- //MaphasSetbehaviorforkeys:
- fill(m,testData1);
- printKeys(m);
- printValues(m);
- print(m);
- Stringkey=testData1[4][0];
- Stringvalue=testData1[4][1];
- System.out.println("m.containsKey(""+key+
- ""):"+m.containsKey(key));
- System.out.println("m.get(""+key+""):"
- +m.get(key));
- System.out.println("m.containsValue(""
- +value+""):"+
- m.containsValue(value));
- Mapm2=fill(newTreeMap(),testData2);
- m.putAll(m2);
- printKeys(m);
- m.remove(testData2[0][0]);
- printKeys(m);
- m.clear();
- System.out.println("m.isEmpty():"
- +m.isEmpty());
- fill(m,testData1);
- //OperationsontheSetchangetheMap:
- m.keySet().removeAll(m.keySet());
- System.out.println("m.isEmpty():"
- +m.isEmpty());
- }
- publicstaticvoidmain(Stringargs[]){
- System.out.println("TestingHashMap");
- test(newHashMap());
- System.out.println("TestingTreeMap");
- test(newTreeMap());
- }
- }///:~
欢迎光临 仓酷云 (http://ckuyun.com/) | Powered by Discuz! X3.2 |