SortedSet集合详解-comparator比较器

/*
让SortedSet集合做到排序还有另一种方式:java.util.Comparator

单独编写一个比较器

1.单独写一个比较器比写一个类实现接口要好,可以重复利用,不需要改动product功能类
2.匿名内部类不推荐使用,因为比较器无法得到重复利用
*/
import java.util.*;


public class fuck12{

public static void main(String[] args){

//创建TreeSet集合的时候提供一个比较器
//因为比较器是接口,不能创建对象,所以要有一个实现类
SortedSet ss=new TreeSet(new productComparator());

//匿名内部类
/*SortedSet ss=new TreeSet(new Comparator()){
public int compare(Object o1,Object o2){

//强制类型转换来调用函数里price变量,再来比较
double price1=((product)o1).price;
double price1=((product)o1).price;

if(price1==price2) return 0;
if(price1<price2){
return 1;
}else(price1>price2){
return -1;
}
}

};*/

//创建对象
product p1=new product(2.3);
product p2=new product(4.3);
product p3=new product(2.4);
product p4=new product(7.3);

//添加元素
ss.add(p1);
ss.add(p2);
ss.add(p3);
ss.add(p4);

//遍历
Iterator it=ss.iterator();
while(it.hasNext()){
System.out.println(it.next());
}


}

}


class product{

double price;

product(double price){
this.price=price;
}

public String toString(){
return price+"";
}
}


//单独编写一个比较器
class productComparator implements Comparator{

public int compare(Object o1,Object o2){

//强制类型转换来调用函数里price变量,再来比较
double price1=((product)o1).price;
double price2=((product)o2).price;

if(price1==price2) {return 0;}
else if(price1<price2){
return 1;
}else{
return -1;
}
}

}

猜你喜欢

转载自blog.csdn.net/rolic_/article/details/80308096