首页 > 其他 > 详细

8.13.2 TreeSet实现Comparable接口的两种方式

时间:2017-08-24 15:55:45      阅读:288      评论:0      收藏:0      [点我收藏+]
推荐使用第二种方式,编写比较器可以使数据类的程序耦合度降低,同时比较器也可以重复利用!
第一种方式:数据类实现Comparable接口,实现其中的compareTo方法
创建对象时,使用TreeSet的默认构造函数!
SortedSet users = new TreeSet();
class User implements Comparable{
//String name;
int age;
User(int age){
this.age = age;
}
public String toString(){
return "User[age="+age+"]";
}
//实现java.lang.Comparable;接口中的compareTo方法
//该方法程序员负责实现,SUN提供的程序已经调用了该方法.
//需求:按照User的age排序
public int compareTo(Object o){
//编写一个比较规则.
int age1 = this.age;
int age2 = ((User)o).age;
return age2-age1;
}
}
第二种方式:单独编写一个实现Comparator接口的比较器,实现其中的compare方法
创建对象时,使用TreeSet的构造函数传入比较器!
SortedSet products = new TreeSet(new Comparator()
class ProductComparator implements Comparator{
//需求:按照商品价格排序
public int compare(Object o1, Object o2){
double price1 = ((Product)o1).price;
double price2 = ((Product)o2).price;
if(price1==price2){
return 0;
}else if(price1>price2){
return 1;
}else{
return -1;
}
}
}

8.13.2 TreeSet实现Comparable接口的两种方式

原文:http://www.cnblogs.com/bchen/p/7423394.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!