JAVA Comparable实例使用

package cn.hfut.www.SortRefType;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.SimpleTimeZone;

/*
* 新闻条目实体类*/
public class NewsItem implements Comparable
{
    private String title;
    private int hits;
    private Date pubtime;

    public NewsItem()
    {
    }

    public NewsItem(String title, int hits, Date pubtime)
    {
        this.title = title;
        this.hits = hits;
        this.pubtime = pubtime;
    }

    public String getTitle()
    {
        return title;
    }

    public void setTitle(String title)
    {
        this.title = title;
    }

    public int getHits()
    {
        return hits;
    }

    public void setHits(int hits)
    {
        this.hits = hits;
    }

    public Date getPubtime()
    {
        return pubtime;
    }

    public void setPubtime(Date pubtime)
    {
        this.pubtime = pubtime;
    }
    //时间降序+点击量升序+标题降序
    @Override
    public int compareTo(NewsItem o)
    {
        int result=0;
        result=-this.pubtime.compareTo(o.pubtime);
        if(result==0){
            result=this.hits-o.hits;
            if(result==0){
                result=this.title.compareTo(o.title);
            }
        }
        return result;
    }

    @Override
    public String toString()
    {
        StringBuilder sb=new StringBuilder();
        sb.append("标题:").append(this.title);
        sb.append("时间:").append(new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(this.pubtime));
        sb.append("点击量:").append(this.hits).append("\n");
        return sb.toString();
    }
}
package cn.hfut.www.SortRefType;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

public class NewsItemApp
{
    public static void main(String[] args)
    {
        List news=new ArrayList();
        news.add(new NewsItem("A",100,new Date()));
        news.add(new NewsItem("B",50,new Date(System.currentTimeMillis()-1000*60*60)));
        news.add(new NewsItem("小日本",50,new Date(System.currentTimeMillis()+1000*60*60)));
        System.out.println("排序前:"+news);
        Collections.sort(news);
        System.out.println("排序后"+news);
    }
}

 

你可能感兴趣的:(Java)