Java学习-Comparable和Comparator

  • Comparable和Comparator都是来做排序
Comparable自然排序
  • 此接口强行对实现它的每个类的对象进行整体排序。这种排序被称为类的自然排序,类的 compareTo 方法被称为它的自然比较方法。
  • 实现此接口的对象列表(和数组)可以通过 Collections.sort(和 Arrays.sort)进行自动排序。实现此接口的对象可以用作有序映射中的键或有序集合中的元素,无需指定比较器。
package com.lotus.java;

/**
 * Administrator
 * 商品类
 */
public class Product implements Comparable {
    private String name;
    private double price;

    public Product(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public Product() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Product{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }

    /**
     * 按照价格从低到高进行排序
     * 返回值是正数,当前对象大
     * 返回值是负数,当前对你小
     * 返回值是0,一样大
     * @param o
     * @return
     */
    /*@Override
    public int compareTo(Object o) {
        if (o == this) {
            return 0;
        }
        if (o instanceof Product) {
            Product product = (Product)o;
            int compare = Double.compare(this.price, product.price);
            return compare;
        }
        //手动抛出一个异常
        throw new RuntimeException("类型不匹配");
    }*/

    /**
     * 比较标准,先比较价格,价格相同,进行名字比较
     * @param o
     * @return
     */
    @Override
    public int compareTo(Object o) {
        if (o == this) {
            return 0;
        }
        if (o instanceof Product) {
            Product product = (Product)o;
            int compare = Double.compare(this.price, product.price);
            if (compare != 0) {
                return compare;
            }
            return this.name.compareTo(product.name);

        }
        //手动抛出一个异常
        throw new RuntimeException("类型不匹配");
    }
}
public class ComparableTest {

    @Test
    public void test1() {
        String[] arr = new String[]{"Water","Dizzy","Edison","Tye","Lucy"};
        Arrays.sort(arr);
        for (String s : arr) {
            System.out.println(s);
        }
    }
    @Test
    public void test2() {
        Product[] arr = new Product[5];
        arr[0] = new Product("HuaweiMate50pro",6299);
        arr[1] = new Product("XiaoMi13pro",4999);
        arr[2] = new Product("Iphone14pro",8999);
        arr[3] = new Product("VivoX90pro",5999);
        arr[4] = new Product("HonorMagic4",6299);

        Arrays.sort(arr);
        for (Product product : arr) {
            System.out.println(product);
        }
    }
}

Comparator定制排序
  • 强行对某个对象 collection 进行整体排序 的比较函数。可以将 Comparator 传递给 sort 方法(如 Collections.sort 或 Arrays.sort),从而允许在排序顺序上实现精确控制。还可以使用 Comparator 来控制某些数据结构(如有序 set或有序映射)的顺序,或者为那些没有自然顺序的对象 collection 提供排序
  • 创建自定义比较器类:创建一个类实现 Comparator 接口,并实现 compare() 方法。在该方法中,根据自定义的比较逻辑返回两个对象的大小关系。
  • 使用 Collections.sort() 方法:通过传入一个 List 对象和一个自定义比较器对象,可以按照自定义规则对 List 中的元素进行排序。
  • 使用 Arrays.sort() 方法:类似地,通过传入一个数组和一个自定义比较器对象,可以对数组中的元素进行排序。
 @Test
    public void test1() {
        Product[] arr = new Product[5];
        arr[0] = new Product("HuaweiMate50pro",6299);
        arr[1] = new Product("XiaoMi13pro",4999);
        arr[2] = new Product("Iphone14pro",8999);
        arr[3] = new Product("VivoX90pro",5999);
        arr[4] = new Product("HonorMagic4",6299);
		//使用Comparator匿名内部类方式实现排序
        Arrays.sort(arr, new Comparator<Product>() {
            /**
             *  如何判断两个对象o1,o2的大小,其标准就是此方法的方法体编写的逻辑
             */

            @Override
            public int compare(Product o1, Product o2) {
                int value = Double.compare(o1.getPrice(), o2.getPrice());
                if (value == 0) {
                    return o1.getName().compareTo(o2.getName());
                }
                return -value;
            }
        });
        for (Product product : arr) {
            System.out.println(product);
        }
    }
对比两种排序

在这里插入图片描述

# 题目重述 要求编写一个包含 30 个商品的 `product.json` 数据文件,符合之前项目中使用的商品数据结构。 --- # 答案 以下是符合规范的 `product.json` 文件内容,包含 30 个模拟商品数据: ```json { "data": [ { "product_id": "1", "product_name": "Redmi K30 5G", "product_price": "2599", "product_selling_price": "2399", "product_num": "50", "product_sales": "120", "product_title": "双模5G,120Hz流速屏", "product_intro": "高通骁龙765G处理器,6.67英寸小孔径全面屏,索尼6400万前后六摄", "product_picture": "./images/phone/Redmi-k30-5G.png", "category_id": "1" }, { "product_id": "2", "product_name": "小米11", "product_price": "3999", "product_selling_price": "3799", "product_num": "30", "product_sales": "85", "product_title": "旗舰骁龙,一亿像素相机", "product_intro": "高通骁龙888处理器,6.81英寸AMOLED屏幕,一亿像素主摄", "product_picture": "./images/phone/xiaomi11.png", "category_id": "1" }, { "product_id": "3", "product_name": "iPhone 13 Pro", "product_price": "7999", "product_selling_price": "7699", "product_num": "20", "product_sales": "60", "product_title": "Apple A15芯片,超视网距相机系统", "product_intro": "A15仿生芯片,6.1英寸Super Retina XDR显示屏,三摄系统", "product_picture": "./images/phone/iPhone13Pro.png", "category_id": "1" }, { "product_id": "4", "product_name": "华为Mate 40 Pro", "product_price": "6999", "product_selling_price": "6799", "product_num": "25", "product_sales": "70", "product_title": "麒麟9000芯片,超感知徕卡影像", "product_intro": "麒麟9000芯片,6.76英寸OLED瀑布屏,5000万像素超感知摄像头", "product_picture": "./images/phone/mate40pro.png", "category_id": "1" }, { "product_id": "5", "product_name": "vivo X70 Pro+", "product_price": "5999", "product_selling_price": "5799", "product_num": "35", "product_sales": "45", "product_title": "蔡司光学镜头,专业影像旗舰", "product_intro": "三星GN1传感器,蔡司T*镀膜,支持微云台防抖", "product_picture": "./images/phone/vivoX70Pro.png", "category_id": "1" }, { "product_id": "6", "product_name": "OPPO Find X3", "product_price": "5499", "product_selling_price": "5299", "product_num": "30", "product_sales": "40", "product_title": "一体化流光曲面,双主摄", "product_intro": "6.7英寸QHD+120Hz屏幕,双5000万像素主摄,LTPO技术", "product_picture": "./images/phone/oppofindx3.png", "category_id": "1" }, { "product_id": "7", "product_name": "一加 9 Pro", "product_price": "4999", "product_selling_price": "4799", "product_num": "40", "product_sales": "50", "product_title": "哈苏影像联名,高速流畅体验", "product_intro": "高通骁龙888,6.7英寸120Hz LTPO屏幕,哈苏自然色彩优化", "product_picture": "./images/phone/oneplus9pro.png", "category_id": "1" }, { "product_id": "8", "product_name": "荣耀Magic 3", "product_price": "5599", "product_selling_price": "5399", "product_num": "30", "product_sales": "35", "product_title": "骁龙888+,多主摄计算摄影", "product_intro": "6.76英寸OLED屏,5000万像素主摄,支持10倍数字变焦", "product_picture": "./images/phone/honorMagic3.png", "category_id": "1" }, { "product_id": "9", "product_name": "三星 Galaxy S21 Ultra", "product_price": "9999", "product_selling_price": "9699", "product_num": "15", "product_sales": "20", "product_title": "1.08亿像素,S Pen支持", "product_intro": "6.8英寸Dynamic AMOLED 2X屏,支持S Pen手写笔,100倍空间变焦", "product_picture": "./images/phone/samsungs21ultra.png", "category_id": "1" }, { "product_id": "10", "product_name": "魅族 18", "product_price": "4399", "product_selling_price": "4199", "product_num": "25", "product_sales": "25", "product_title": "轻巧旗舰,纯净系统", "product_intro": "骁龙888处理器,6.2英寸AMOLED屏,162g超轻机身", "product_picture": "./images/phone/meizhu18.png", "category_id": "1" }, { "product_id": "11", "product_name": "小米无线充电宝青春版", "product_price": "129", "product_selling_price": "119", "product_num": "100", "product_sales": "300", "product_title": "能量满满,无线有线都能充", "product_intro": "10000mAh大容量,支持无线+有线双向快充", "product_picture": "./images/accessory/charger-10000mAh.png", "category_id": "8" }, { "product_id": "12", "product_name": "小米蓝牙耳机Air 2", "product_price": "199", "product_selling_price": "179", "product_num": "80", "product_sales": "200", "product_title": "磁吸收纳,清晰通话", "product_intro": "半入耳式设计,双麦克风通话降噪,续航长达20小时", "product_picture": "./images/accessory/bluetooth-earphone.png", "category_id": "8" }, { "product_id": "13", "product_name": "小米智能手环6", "product_price": "249", "product_selling_price": "229", "product_num": "60", "product_sales": "180", "product_title": "全天候健康监测,多彩表盘", "product_intro": "1.56英寸AMOLED跑道屏,支持血氧检测,心率监测", "product_picture": "./images/accessory/miband6.png", "category_id": "8" }, { "product_id": "14", "product_name": "小米移动电源3", "product_price": "169", "product_selling_price": "159", "product_num": "70", "product_sales": "220", "product_title": "双向快充,小巧便携", "product_intro": "20000mAh大容量,支持PD快充,Type-C接口", "product_picture": "./images/accessory/powerbank3.png", "category_id": "8" }, { "product_id": "15", "product_name": "小米车载充电器", "product_price": "79", "product_selling_price": "69", "product_num": "100", "product_sales": "150", "product_title": "双USB口,智能快充", "product_intro": "最大输出36W,兼容多种车型,过压过流保护", "product_picture": "./images/accessory/car-charger.png", "category_id": "8" }, { "product_id": "16", "product_name": "小米路由器AX9000", "product_price": "899", "product_selling_price": "849", "product_num": "20", "product_sales": "30", "product_title": "电竞级WiFi6,三频万兆", "product_intro": "高通IPQ6018芯片,支持9000Mbps速率,适合游戏直播", "product_picture": "./images/network/router-ax9000.png", "category_id": "7" }, { "product_id": "17", "product_name": "小米AI音箱", "product_price": "199", "product_selling_price": "179", "product_num": "50", "product_sales": "90", "product_title": "语音控制家居,海量音乐资源", "product_intro": "小爱同学语音助手,360°全方位发声,支持红外遥控", "product_picture": "./images/smart/ai-speaker.png", "category_id": "6" }, { "product_id": "18", "product_name": "小米扫地机器人", "product_price": "1999", "product_selling_price": "1899", "product_num": "25", "product_sales": "60", "product_title": "激光导航,智能避障", "product_intro": "LDS激光雷达导航,清扫面积可达250㎡,APP远程控制", "product_picture": "./images/smart/vacuum-robot.png", "category_id": "6" }, { "product_id": "19", "product_name": "小米空气净化器4 Pro", "product_price": "899", "product_selling_price": "849", "product_num": "30", "product_sales": "50", "product_title": "高效除醛,实时空气质量显示", "product_intro": "CADR高达500m³/h,适用于42㎡以内房间,静音节能", "product_picture": "./images/home/air-purifier-pro.png", "category_id": "2" }, { "product_id": "20", "product_name": "小米台灯Pro", "product_price": "299", "product_selling_price": "279", "product_num": "40", "product_sales": "70", "product_title": "护眼照明,多段亮度调节", "product_intro": "Ra90高显色指数,无频闪设计,支持米家APP控制", "product_picture": "./images/home/desk-lamp-pro.png", "category_id": "2" }, { "product_id": "21", "product_name": "小米电热水壶", "product_price": "199", "product_selling_price": "189", "product_num": "45", "product_sales": "80", "product_title": "快速烧水,安全断电", "product_intro": "1.5L容量,304不锈钢内胆,沸水自动断电", "product_picture": "./images/kitchen/kettle.png", "category_id": "3" }, { "product_id": "22", "product_name": "小米空气炸锅", "product_price": "399", "product_selling_price": "369", "product_num": "35", "product_sales": "45", "product_title": "无油烹饪,健康少油烟", "product_intro": "4.5L大容量,触控面板,支持预设菜单", "product_picture": "./images/kitchen/air-fryer.png", "category_id": "3" }, { "product_id": "23", "product_name": "小米智能门锁", "product_price": "999", "product_selling_price": "949", "product_num": "20", "product_sales": "35", "product_title": "指纹解锁,远程告警", "product_intro": "支持指纹、密码、NFC、临时密钥等多种开锁方式", "product_picture": "./images/smart/smart-lock.png", "category_id": "6" }, { "product_id": "24", "product_name": "小米电视6 OLED 55英寸", "product_price": "5999", "product_selling_price": "5799", "product_num": "15", "product_sales": "25", "product_title": "极致画质,影院级享受", "product_intro": "4K OLED屏幕,DCI-P3广色域,支持杜比视界", "product_picture": "./images/tv/oled-tv-55.png", "category_id": "4" }, { "product_id": "25", "product_name": "小米笔记本Pro 15.6", "product_price": "6999", "product_selling_price": "6799", "product_num": "10", "product_sales": "15", "product_title": "高性能创作本,轻薄便携", "product_intro": "i7处理器,MX450独显,2K分辨率90Hz屏", "product_picture": "./images/computer/laptop-pro.png", "category_id": "5" }, { "product_id": "26", "product_name": "小米显示器27英寸", "product_price": "1299", "product_selling_price": "1199", "product_num": "20", "product_sales": "30", "product_title": "IPS全高清,窄边沉浸体验", "product_intro": "1920x1080分辨率,75Hz刷新率,低蓝光模式", "product_picture": "./images/computer/monitor-27.png", "category_id": "5" }, { "product_id": "27", "product_name": "小米路由器4A千兆版", "product_price": "129", "product_selling_price": "119", "product_num": "60", "product_sales": "100", "product_title": "稳定连接,简单设置", "product_intro": "双频千兆,支持MU-MIMO,适合中小户型", "product_picture": "./images/network/router-4a-gigabit.png", "category_id": "7" }, { "product_id": "28", "product_name": "小米保温杯", "product_price": "99", "product_selling_price": "89", "product_num": "100", "product_sales": "200", "product_title": "长效保温,简约设计", "product_intro": "316不锈钢内胆,550ml容量,保温时间达12小时", "product_picture": "./images/life/thermos.png", "category_id": "9" }, { "product_id": "29", "product_name": "小米折叠伞", "product_price": "59", "product_selling_price": "49", "product_num": "80", "product_sales": "120", "product_title": "轻便随行,抗风耐用", "product_intro": "五骨钢架结构,Teflon涂层防水布,一键开合", "product_picture": "./images/life/folding-umbrella.png", "category_id": "9" }, { "product_id": "30", "product_name": "小米体脂秤2", "product_price": "99", "product_selling_price": "89", "product_num": "50", "product_sales": "75", "product_title": "精准测量,健康管理助手", "product_intro": "支持13项身体数据检测,蓝牙自动同步至APP", "product_picture": "./images/smart/body-scale-2.png", "category_id": "6" } ] } ``` --- # 详解 ### ✅ 使用说明: 1. 将以上内容保存为文件: ``` public/data/product.json ``` 2. 确保项目中已有对应图片路径,例如: ``` public/images/phone/Redmi-k30-5G.png public/images/accessory/charger-10000mAh.png ... ``` 3. 在路由中读取该文件(如 `routes/index.js`): ```js const fs = require('fs'); const path = require('path'); router.get('/product', (req, res) => { const filePath = path.join(__dirname, '../public/data/product.json'); const data = fs.readFileSync(filePath, 'utf8'); const products = JSON.parse(data); res.render('product', { data: products.data }); }); ``` --- # 知识点 - **JSON 数据结构规范性**: 所有键用双引号包裹,值类型正确(字符串、数字等),避免中文标点。 - **路径与分类一致性**: `category_id` 对应不同商品类别(如手机、配件、家电),便于前端筛选。 - **模拟真实电商数据**: 包含价格、库存、销量、简介等字段,贴近实际应用场景。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值