孤好梦中杀人 2014-07-31 16:38
浏览 249
已采纳

部分排序(Comparable)怎么做

[code="java"]
import java.util.Date;

public class User implements Comparable
{

private Integer userid;

//年龄
private Integer age;

//注册日期
private Date regDate;

/**
 * 1 :首先,把age=30的拿出来,先排序,regDate大的排序在前面
 * 2 :然后,排序age!=30的,regDate大的排序在前面 
 */
public int compareTo(User o)
{
    return 0;
}

}
[/code]

排序逻辑见上面的注释

比如说,有如下数据
1 20 2013-01-21
2 30 2013-04-25
3 19 2013-11-14
4 55 2013-03-16
5 30 2013-02-20

排序后的结果为:

2 30 2013-04-25
5 30 2013-02-20
3 19 2013-11-14
4 55 2013-03-16
1 20 2013-01-21

请问,怎么做

  • 写回答

4条回答 默认 最新

  • tianchao_ 2014-07-31 18:34
    关注

    [quote]
    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Collections;
    import java.util.Date;

    public class User implements Comparable {

    private Integer userid;
    
    // 年龄
    private Integer age;
    
    // 注册日期
    private Date regDate;
    
    public User(Integer userid, Integer age, Date regDate) {
        this.userid=userid;
        this.age=age;
        this.regDate=regDate;
    }
    
    /**
     * 1 :首先,把age=30的拿出来,先排序,regDate大的排序在前面 2 :然后,排序age!=30的,regDate大的排序在前面
     */
    @Override
    public int compareTo(User o) {
        if (this.age == 30 && o.age == 30) {
            return o.regDate.compareTo( this.regDate);
        } else if (this.age == 30) {
            return -1;
        } else if (o.age == 30) {
            return 1;
        } else {
            return o.regDate.compareTo(this.regDate);
        }
    }
    
    @Override
    public String toString() {
        return this.userid+" "+this.age+" ";
    }
    
    public static void main(String[] args) throws ParseException {
        /*
         * 1 20 2013-01-21 2 30 2013-04-25 3 19 2013-11-14 4 55 2013-03-16 5 30
         * 2013-02-20
         */
    
        ArrayList<User> list = new ArrayList<User>();
        DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        User u1 = new User(1, 20, format1.parse("2013-01-21"));
        User u2 = new User(2, 30, format1.parse("2013-04-25"));
        User u3 = new User(3, 19, format1.parse("2013-11-14"));
        User u4 = new User(4, 55, format1.parse("2013-03-16"));
        User u5 = new User(5, 30, format1.parse("2013-02-20"));
        list.add(u1);
        list.add(u2);
        list.add(u3);
        list.add(u4);
        list.add(u5);
    
        System.out.println(list);
        Collections.sort(list);
        System.out.println(list);
    
    }
    

    }
    [/quote]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页