SortedSet接口与TreeSet实现类(二)

来源:互联网 发布:各编程语言比较 编辑:程序博客网 时间:2024/06/06 07:28
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;        }    }}
0 0
原创粉丝点击