import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* 练习17:使用练习1中的Gerbil类,将其放入Map中,将每个Gerbil的名字(例如Fuzzy或Spot)String(键)与每个Gerbil(值)关联起来。为keySet()获取Iterator,使用它遍历Map,
* 针对每个"键"查询Gerbil,然后打印出"键",并让gerbil执行hop()
*/
public class Excrcise17 {
public static void excr(Map<String, Gerbil> map) {
Set<String> keySet = map.keySet();
Iterator<String> it = keySet.iterator();
while (it.hasNext()) {
String key = it.next();
Gerbil gerbil = map.get(key);
System.out.print(key + " ");
gerbil.hop();
}
}
public static void main(String[] args) {
Map<String, Gerbil> stringGerbilMap = new HashMap<String, Gerbil>();
Gerbil gerbil1 = new Gerbil(1);
Gerbil gerbil2 = new Gerbil(2);
Gerbil gerbil3 = new Gerbil(3);
Gerbil gerbil4 = new Gerbil(4);
stringGerbilMap.put("Fuzzy", gerbil1);
stringGerbilMap.put("Spot", gerbil2);
stringGerbilMap.put("Bob", gerbil3);
stringGerbilMap.put("Keven", gerbil4);
excr(stringGerbilMap);
}
}
class Gerbil {
private int gerbilNumber;
public Gerbil(int gerbilNumber) {
this.gerbilNumber = gerbilNumber;
}
public void hop() {
System.out.println(gerbilNumber+" hop hop !");
}
}
/* Output:
Bob 3 hop hop !
Spot 2 hop hop !
Keven 4 hop hop !
Fuzzy 1 hop hop !
*///:~