1 .Main |
package s0223多条件排序; |
import java.util.ArrayList; |
import java.util.Collections; |
import java.util.Date; |
import java.util.List; |
public class Main { |
public static void main(String[] args) { |
List<NewsItem> news= new ArrayList<NewsItem>(); |
news.add( new NewsItem( "中国登上钓鱼岛" , 100 , new Date(System.currentTimeMillis() ) ) ); |
news.add( new NewsItem( "中国GDP总量" , 40 , new Date(System.currentTimeMillis() ) ) ); |
news.add( new NewsItem( "美国总统与xx会晤" , 60 , new Date(System.currentTimeMillis() ) ) ); |
|
System.out.println( "排序前:" +news); |
Collections.sort(news); |
//因为news中的元素都是Comparable的实现类的实例,所以默认使用指定的Comparator |
//如果使用comparator的实现类,那么要指定comparator |
System.out.println( "排序后:" +news); |
} |
} |
2 .NewsItem类,在这个类中定义了排序优先级和排序顺序 |
package s0223多条件排序; |
import java.text.SimpleDateFormat; |
//新闻按时间降序,点击量升序,标题降序 |
import java.util.Date; |
public class NewsItem implements java.lang.Comparable<NewsItem>{ |
private String title; |
private int hit; |
private Date pubTime; |
|
public NewsItem(){} |
public NewsItem(String title, int hit, Date pubTime) |
{ |
super (); |
this .title = title; |
this .hit = hit; |
this .pubTime = pubTime; |
} |
|
//新闻按时间降序,点击量升序,标题降序,3个if嵌套,规定了排序的优先级 |
public int compareTo(NewsItem o) |
{ |
int result= 0 ; |
result=- this .pubTime.compareTo(o.pubTime); //加了- 变成降序 |
if (result== 0 ) |
{ |
result= this .hit-o.hit; |
if (result== 0 ) |
{ |
result= this .title.compareTo(o.title); |
} |
} |
return result; |
} |
|
public String toString() |
{ |
StringBuilder sb= new StringBuilder(); |
sb.append( " 标题:" ).append( this .title); |
sb.append( " 时间:" ).append( new SimpleDateFormat( "yyyy-MM-dd" ).format( this .pubTime)); |
sb.append( " 点击量:" ).append( this .hit).append( "\n" ); |
String str=sb.toString(); |
return str; |
} |
public String getTitle() { |
return title; |
} |
public void setTitle(String title) { |
this .title = title; |
} |
public int getHit() { |
return hit; |
} |
public void setHit( int hit) { |
this .hit = hit; |
} |
public Date getPubTime() { |
return pubTime; |
} |
public void setPubTime(Date pubTime) { |
this .pubTime = pubTime; |
} |
|
|
|
} |