解答例 - 実習課題2 - 4.Map
(実習課題2)
実習課題1のプログラムを改良しなさい。
- 「HashMap」の代わりに「TreeMap」を使用すること。}
解答例
package com.techscore.utility.chapter4.exercise2;
/**
* ComparableHuman.java
* TECHSCORE Javaユーティリティ4章 実習課題2
*
* Copyright (c) 2004 Four-Dimensional Data, Inc.
*/
public class ComparableHuman extends Human implements Comparable {
public ComparableHuman(String name, int age) {
super(name, age);
}
// 年齢を比較する。年齢が同じなら true を返す。
public boolean equals(Human h) {
return (this.getAge() == h.getAge());
}
// 年齢を比較する。年齢差を返す。
public int compareTo(Object obj) {
return (this.getAge() - ((Human) obj).getAge());
}
}
package com.techscore.utility.chapter4.exercise2;
/**
* Human.java
* TECHSCORE Javaユーティリティ4章 実習課題2
*
* Copyright (c) 2004 Four-Dimensional Data, Inc.
*/
public class Human {
private String name = null;
private int age = 0;
public Human(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return (name);
}
public int getAge() {
return (age);
}
}
package com.techscore.utility.chapter4.exercise2;
import java.util.Iterator;
import java.util.Set;
import java.util.Map;
import java.util.TreeMap;
/**
* TreeMapExample.java
* TECHSCORE Javaユーティリティ4章 実習課題2
*
* Copyright (c) 2004 Four-Dimensional Data, Inc.
*/
public class TreeMapExample {
public static void main(String[] args) {
// ツリーマップを初期化する。
TreeMap map = new TreeMap();
// 追加する人のオブジェクトを作成する。
ComparableHuman taro = new ComparableHuman("太郎", 15);
ComparableHuman hanako = new ComparableHuman("花子", 12);
ComparableHuman jiro = new ComparableHuman("次郎", 13);
// ツリーマップにHumanオブジェクトを追加する。
map.put(taro, "京都市左京区");
map.put(hanako, "大阪市北区");
map.put(jiro, "神戸市中央区");
// ツリーマップの一覧を表示する。
Set set = map.entrySet();
Iterator i = set.iterator();
while (i.hasNext()) {
Map.Entry entry = (Map.Entry) i.next();
ComparableHuman h = (ComparableHuman) entry.getKey();
System.out.println(
"(名前)"
+ h.getName()
+ " (年齢)"
+ h.getAge()
+ " (住所)"
+ entry.getValue());
}
}
}

