容易遗忘的Comparable:一个结果集List,里面有很多的对象,要求根据对象的指定(age)字段进行排序

 
要排序的User bean要实现Comparable接口,重写 compareTo方法,面试过程中被问到的时候很可能会思考短路哦

 

package com.jiaocaigen; 

  

import java.util.*; 

  

public class SortTest { 

    public static void main(String[] args) { 

       List<User> c = new ArrayList(); 

       c.add( new User(10, "zs1" )); 

       c.add( new User(20, "zsxy" )); 

       c.add( new User(20, "zs2" )); 

       c.add( new User(40, "zs4" )); 

       c.add( new User(30, "zs3" )); 

       c.add( new User(50, "zs5" )); 

       

       // 正序 

       Collections.sort((List<User>) c); 

       // 逆序:只需先正序再翻转 

//     Collections.reverse((List<User>) c); 

       

       System. out .println(c); 

    } 

} 

/** 

  * 

  * 需要排序的 bean 对象 

  * 

  * 用例是这样的 

  * 一个结果集 List ,里面有很多的对象,要求根据对象的 age 字段进行排序。 

  * @author 雷伟 2011 - 9 - 11 

  */ 

class User implements Comparable{

    

    private int age ; 

    private String name ; 

    

    

    public User() { 

       super (); 

    } 

    

    public User( int age, String name) {

       super (); 

       this . age = age; 

       this . name = name; 

    } 

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; 

    } 

  

    /*  

     * 按照 id 从小到大的顺序排序。 自己可以在方法里面编写任意的排序算法。   

     */   

    public int compareTo(Object o) { 

       User user = (User) o; 

       

       // 根据 ID 从小到大顺序。 

       if ( this . age > user.getAge()){

           return 1; 

       } else if ( this . age < user.getAge()){

           return -1; 

       } else { 

           return 0; 

       } 

    } 

// 重写 toString 方法 

    public String toString() { 

       return this . age + " " + this . name ; 

    } 

} 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值