TreeSet自定义比较器

TreeSet是一个有序的集合,它的作用是提供有序的Set集合。它继承了AbstractSet抽象类,实现了NavigableSet,Cloneable,Serializable接口。TreeSet是基于TreeMap实现的,TreeSet的元素支持2种排序方式:自然排序或者根据提供的Comparator进行排序。

  • 自然排序需要继承被排序的类并实现Comparable接口,实现其中的compareTo方法并自定义对象转换器
  • 自定义排序只需要实现Comparator并实现其compareTo方法
/**** 实现了Comparable接口的产品类,以支持自然排序 ****/
public class ComparableProduct extends Product implements Comparable {
    public ComparableProduct(int id, String name, int inventory) {
        super(id, name, inventory); // 调用父类的构造方法
    }

    /**** 重写Comparable接口的方法 ****/
    public int compareTo(Object o) {
        ComparableProduct p = (ComparableProduct) o; // 造型
        return p.getId() - this.getId(); // p的编号减去当前产品编号(即以编号降序排列)
    }

    /**** 将Product对象转为ComparableProduct对象 ****/
    public static ComparableProduct from(Product p) {
        int id = p.getId(); // 得到原产品对象的各个属性
        String name = p.getName();
        int inventory = p.getInventory();
        return new ComparableProduct(id, name, inventory);
    }
}
/**** 实现Comparator接口的比较器类,以支持自定义排序 ****/
public class ProductComparator implements Comparator {
    /**** 重写Comparator接口的方法 ****/
    public int compare(Object o1, Object o2) {
        Product p1 = (Product) o1; // 造型为产品对象
        Product p2 = (Product) o2;
        return p1.getInventory() - p2.getInventory(); // 以库存升序排列
    }
}
public class TreeSetDemo {
    public static void main(String[] args) {
        TreeSet set1 = new TreeSet(); // 构造树形集合(默认使用自然排序)

        ProductComparator comparator = new ProductComparator(); // 构造比较器对象
        TreeSet set2 = new TreeSet(comparator); // 构造树形集合(指定了比较器,使用自定义排序)

        Product[] ps = ProductUtil.createProducts(); // 生成产品数组
        for (Product p : ps) {
            ComparableProduct cp = ComparableProduct.from(p);
            set1.add(cp); // 添加转换后的产品到set1
            set2.add(p); // 添加原产品到set2
        }

        System.out.println("set1的元素(自然排序):");
        ProductUtil.printProducts(set1);
        System.out.println("set2的元素(自定义排序):");
        ProductUtil.printProducts(set2);

        Product low = (Product) set2.first(); // 得到最小的产品
        System.out.println("库存最少:" + low.getName());
        Product high = (Product) set2.last(); // 得到最大的产品
        System.out.println("库存最多:" + high.getName());

        Product target = new Product(9, "--", 150); // 用于比较的目标产品
        /**** 打印所有大于等于目标的产品 ****/
        TreeSet set3 = (TreeSet) set2.tailSet(target);
        System.out.print("库存超过" + target.getInventory() + "(含):");
        for (Object o : set3) { // 迭代
            Product p = (Product) o;
            System.out.print(p.getName() + " ");
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值