java ArrayList排序2009-01-06 13:37常常遇到數(shù)組排序的問題.比如我有一個Person類,它的實例對象存儲在ArrayList數(shù)組中,現(xiàn)在要把ArrayList數(shù)組中的Person對象按照年齡排序.
其實這種情況經(jīng)常遇到. 下面給出源代碼: 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------------------------------- //實現(xiàn)Comparator接口,也就是定義排序規(guī)則,你幾乎可以定義任何規(guī)則 package com.infoearth; 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------------------------------------ package com.infoearth; 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()); } } } |
|