(1)TreeSet里面的元素是按照顺序排序的,那么就是说明,他的元素必须使用comparable接口的类,并且实现里面的compareTo方法,
不然两个元素怎么比较
new TreeSet();
(2)如果类不实现Comparable,还有一种,就是要做一个排序业务类,这个类要实现java.util.Comparator接口+compare方法,
new TreeSet(Comparator<? extends Comparator> comparator)
public class Demo4 {
public static void main(String[] args) {
NewItem newItem1 = new NewItem("火星撞地球",100,new Date());
NewItem newItem2 = new NewItem("月全食",10,new Date(System.currentTimeMillis()-500000));
NewItem newItem3 = new NewItem("太阳风暴",20,new Date());
MyComparator<NewItem> com = new MyComparator<NewItem>();
TreeSet<NewItem> treeSet = new TreeSet<NewItem>(com);
class MyComparator<T extends NewItem> implements Comparator<T>{
@Override
public int compare(T o1, T o2) {
int result = -(o1.getDate().compareTo(o2.getDate()));
if(result==0){
result = -(o1.getActive()-o2.getActive());
if(result==0){
result = o1.getName().compareTo(o2.getName());
}
}
return result;
}
class NewItem {
private final String name;//新闻名
private final int active;//点击量
private final Date date;//发布时间
public NewItem(String name,int active,Date date){
this.name=name;
this.active=active;
this.date=date;
}
public String getName() {
return name;
}
public int getActive() {
return active;
}
public Date getDate() {
return date;
}
@Override
public String toString() {
DateFormat df = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
String time = df.format(this.date);
return "新闻标题:"+this.name+" 点击量:"+this.active+" 发表时间:"+time;
}
}