java123-treeset排序集合

import java.util.Comparator;
 
public class GoodsSorts implements Comparator {
    public int compare(Object o1,Object o2){
        Goods g1=(Goods)o1;
        Goods g2=(Goods)o2;
        System.out.println("调用排序方法");
        if(g1.getPrice()>g2.getPrice()){
            return -1;
        }else if(g1.getPrice()<g2.getPrice()){
            return 1;
        }
        return 0;
    }
}
测试类

import java.util.TreeSet;
 
public class test63 {
    public static void main(String[] args){
        TreeSet tree=new TreeSet(new GoodsSorts());//创建一个采用默认树形自然排序的对象
        Goods g0=new Goods();
        g0.setName("剃须刀");
        g0.setPrice(2000.0);
        Goods g1=new Goods();
        g1.setName("西瓜");
        g1.setPrice(7000.0);
        Goods g2=new Goods();
        g2.setName("小刀");
        g2.setPrice(3000.0);
        Goods g3=new Goods();
        g3.setName("矿泉水");
        g3.setPrice(4000.0);
        tree.add(g3);
        tree.add(g2);
        tree.add(g1);
        tree.add(g0);
        for(Object o:tree){
            System.out.println(((Goods)o).getName()+"\t"+((Goods)o).getPrice());
        }
        System.out.println("第一个"+((Goods)tree.first()).getName());
        System.out.println("最后一个"+((Goods)tree.last()).getName());
    }
}
运行结果

 

posted @   前端导师歌谣  阅读(21)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示