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;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值