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 © 負人博客

          主站蜘蛛池模板: 石台县| 嘉黎县| 成武县| 平阳县| 浦城县| 汝阳县| 大化| 普宁市| 格尔木市| 汪清县| 舒兰市| 永福县| 湛江市| 资兴市| 武鸣县| 东兰县| 商城县| 自贡市| 冷水江市| 衡东县| 全南县| 嫩江县| 泾川县| 林芝县| 云梦县| 伊金霍洛旗| 阿坝县| 阜南县| 新营市| 竹山县| 岫岩| 临邑县| 共和县| 林甸县| 蒙山县| 吉木乃县| 瑞昌市| 聊城市| 蕲春县| 江口县| 台北县|