写的不错:
- package com.test;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.Iterator;
- import java.util.List;
- public class MySort {
- public static void main(String[] args) {
- List<User> list=new ArrayList<User>();
- list.add(new User("wangwu",24));
- list.add(new User("wangwu",23));
- list.add(new User("wangwu",27));
- list.add(new User("wangwu",29));
- list.add(new User("wangwu",21));
- Print(list);
- Collections.sort(list, new MyCompare());//调用排序方法,传入自己的比较器
- Print(list);
- }
- //定义一个打印方法
- public static void Print(List<User> list){
- Iterator<User> it=list.iterator();
- System.out.print("[");
- while(it.hasNext()){
- User u=it.next();
- System.out.print(u.getName()+":"+u.getAge()+" ");
- }
- System.out.println("]");
- }
- }
- class User{
- private String name;
- private int age;
- User(String name,int age){
- this.age=age;
- this.name=name;
- }
- public String getName(){
- return this.name;
- }
- public int getAge(){
- return this.age;
- }
- }
- //定义自己的比较器
- class MyCompare implements Comparator<User>{
- public int compare(User u1,User u2){
- int num=u1.getAge()-u2.getAge();
- if(num==0)
- return u1.getName().compareTo(u2.getName());
- return num;
- }
- }
复制代码 |