Java > TreeMapの使い方

更新日 2011-12-09
広告
TreeMapの使い方を紹介します。
Setインターフェースを実装しているクラス(HashSetなど)は、重複を許さないリストとして利用するのに向いています。
重複を許さず、さらに、要素をソートして管理したい場合は、SortedSetをインターフェースを利用します。 TreeSetクラスは、SortedSetインターフェースの実装するクラスの1つです。
SortedSetでソートするクラスは、Comparableインターフェースを実装している必要があります。 今回は、「Comparableの使い方」でも利用した Human クラスをソートします。
public class Human implements Comparable<Human> {
    // 名前
    private final String name;

    // 年齢
    private final int age;

    // 体重
    private final double weight;

    // コンストラクタ
    public Human(String name, int age, double weight) {
    	this.name = name;
    	this.age = age;
    	this.weight = weight;
    }

    public String getName() {
    	return this.name;
    }

    public int getAge() {
    	return this.age;
    }

    public double getWeight() {
    	return this.weight;
    }

    @Override
    public int compareTo(Human otherHuman) {
    	if (this.age < otherHuman.getAge()) {
    	    return -1;
    	} else if (this.age >= otherHuman.getAge()) {
    	    return 1;
    	} else {
    	    return 0;
    	}
    }

    @Override
    public String toString() {
    	return "(" + this.name + ", " + this.age + ", " + this.weight + ")";
    }
}
HumanクラスはComparableインターフェースを実装しており、「年齢が若い順にソートする」ようにcompareToメソッドを実装しています(詳細は「Comparableの使い方」)。
以下のサンプル SortedSetTest では、TreeMapを使ってHumanクラスをソートします。
import java.util.*;

public class SortedSetTest {
    public static void main(String[] args) {
    	Human ichiro = new Human("ichiro", 15, 50.8); // 一郎は15歳
    	Human jiro = new Human("jiro", 13, 43.2);   // 二郎は13歳
    	Human saburo = new Human("saburo", 11, 40.7); // 三郎は11歳

    	// TreeSetに三兄弟をセット
    	SortedSet<Human> brotherSet = new TreeSet<Human>();
    	brotherSet.add(jiro);
    	brotherSet.add(saburo);
    	brotherSet.add(ichiro);

    	// 順番に表示
    	for (Human human : brotherSet) {
    	    System.out.println(human);
    	}
	
    	System.out.println("");

    	// 先頭を表示
    	System.out.println("first = " + brotherSet.first());

    	// 最後を表示
    	System.out.println("last  = " + brotherSet.last());
    }
}
これを実行すると、以下の結果になります。
SortedSet$ java SortedSetTest 
(saburo, 11, 40.7)
(jiro, 13, 43.2)
(ichiro, 15, 50.8)

first = (saburo, 11, 40.7)
last  = (ichiro, 15, 50.8)
三兄弟が年齢順にソートされていることがわかります。
広告
お問い合わせは sweng.tips@gmail.com まで。
inserted by FC2 system