Comparator接口

          Posted on 2006-07-06 18:18 負人博客 閱讀(1210) 評論(0)  編輯  收藏 所屬分類: JAVA技術

          List的排序是經常遇到的問題,一般都是用一個實現了Comparator接口的類實現。
          .比如我有一個Person類,
          它的實例對象存儲在ArrayList數組中,現在要把ArrayList數組中的Person對象按照年齡排序.
          其實這種情況經常遇到.
          下面給出源代碼:

          1:Person.java文件:-------------------------------
          public class Person{
          ?String name;
          ?int age;
          ?
          ?public Person(String name,int age){
          ? this.name = name;
          ? this.age = age;
          ?
          ?}

          ?public int getAge() {
          ? return age;
          ?}

          ?public void setAge(int age) {
          ? this.age = age;
          ?}

          ?public String getName() {
          ? return name;
          ?}

          ?public void setName(String name) {
          ? this.name = name;
          ?}

          }


          2:Mycomparator.java-------------------------------
          //實現Comparator接口,也就是定義排序規則,你幾乎可以定義任何規則
          import java.util.*;
          public class Mycomparator implements Comparator{

          ?public int compare(Object o1,Object o2) {
          ? Person p1=(Person)o1;
          ? Person p2=(Person)o2;?
          ? if(p1.age<p2.age)
          ?? return 1;
          ? else
          ?? return 0;
          ?}

          }

          3:ListSort.java------------------------------------

          import java.util.ArrayList;
          import java.util.Collections;
          import java.util.Comparator;

          public class ListSort {
          ?public static void main(String[] args){
          ? ArrayList list = new ArrayList();
          ? list.add(new Person("lcl",28));
          ? list.add(new Person("fx",23));
          ? list.add(new Person("wqx",29));
          ? Comparator comp = new Mycomparator();
          ? Collections.sort(list,comp);?
          ? for(int i = 0;i<list.size();i++){
          ?? Person p = (Person)list.get(i);
          ?? System.out.println(p.getName());
          ? }?
          ?
          ?}

          }


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           

          posts - 26, comments - 5, trackbacks - 0, articles - 8

          Copyright © 負人博客

          主站蜘蛛池模板: 杨浦区| 平舆县| 延边| 红原县| 石棉县| 江达县| 且末县| 唐河县| 离岛区| 东阳市| 元氏县| 乡城县| 两当县| 绩溪县| 三亚市| 华宁县| 房产| 晋中市| 莆田市| 韶关市| 洛川县| 堆龙德庆县| 临沂市| 梁山县| 涟源市| 武夷山市| 隆安县| 永泰县| 墨竹工卡县| 乐业县| 岫岩| 双流县| 河曲县| 荥经县| 航空| 永安市| 宁德市| 申扎县| 正定县| 六枝特区| 肥城市|