collectionでのクラスのソート

2105 ワード

まずpersonクラスを書いて彼にComparable構造関数とget/setを継承させるのは言うまでもない.
親クラスのcompartoメソッドコードを上書きするにはget/setを省略します.
package a;

public class Person implements Comparable<Person> {
	private int age;
	private String name;

	public Person(int age, String name) {
		this.age = age;
		this.name = name;
	}	
	public int compareTo(Person o) {
		return this.getAge()-o.getAge();
	}
	
	public void show(){
		System.out.println("      "  +name +"    "+age);
	}

}

テストコードは以下のように説明する必要はありません...
package a;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class TestComparable {
    public static void main(String args[]) {

        List<Person> listCat1 = new ArrayList<Person>();
        listCat1.add(new Person(35, "hlf"));
        listCat1.add(new Person(36, "ddd"));
        listCat1.add(new Person(38, "xxx"));

        System.out.println("  Collections.sort(List<T> list)listCat2    :");
        Collections.sort(listCat1);
        for (int i = 0; i < listCat1.size(); i++) {
            listCat1.get(i).show();
        }

        System.out.println("      :");
        Collections.sort(listCat1, Collections.reverseOrder());
        for (int i = 0; i < listCat1.size(); i++) {
            listCat1.get(i).show();
        }
        System.out.println("Collections.reverse               :");
        Collections.reverse(listCat1);
        for (int i = 0; i < listCat1.size(); i++) {
            listCat1.get(i).show();
        }
    }
}
テスト結果
Collectionsを呼び出す.sort(Listlist)listCat 2昇順ソート:氏名hlf年齢35氏名ddd年齢36氏名xxx年齢38降順ソート要素:氏名xxx年齢38氏名ddd年齢36氏名hlf年齢35 Collections.reverseリストの最後の要素から出力:名前hlf年齢35名前ddd年齢36名前xxx年齢38
これはintタイプで並べ替えますstringで並べ替えたいなら簡単ですpersonクラスのcomparetoは次のように変更してOKです
    public int compareTo(Person o) {
       return this.getName().compareTo(o.getName());
    }

参考資料
JAvaコレクションソートhttp://www.cnblogs.com/standcloud/articles/2601914.html