SortedSet接口与TreeSet实现类(二)

package cn.kcn.set;
import java.util.*;
/* * 让SortedSet集合做到排序还有另一种方式:java.util.Comparator; * 单独编写一个比较器 */
public class SortedSetTest02 {

    public static void main(String[] args) {
        //创建TreeSet集合时候提供一个比较器
        SortedSet ss = new TreeSet(new ProductComparator());

        Product p1 = new Product(3.5);
        Product p2 = new Product(5.3);
        Product p3 = new Product(7.8);
        Product p4 = new Product(8.9);
        Product p5 = new Product(6.1);
        ss.add(p1);
        ss.add(p2);
        ss.add(p3);
        ss.add(p4);
        ss.add(p5);

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

}
//商品类
class Product{
    double price;//商品价格
    Product(double price){
        this.price = price;
    }
    @Override
    public String toString() {
        return price+"";
    }

}
//单独编写一个比较器
class ProductComparator implements Comparator{
    //需求:按照商品价格排序
    public int compare(Object o1,Object o2){
        //对o1,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;
        }
    }
}

你可能感兴趣的:(comparator,TreeSet,SortedSet)