题解 | #集合排序#

集合排序

https://www.nowcoder.com/practice/4d12899bb255459bbf2b3635b3d32817

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Customer customer1 = new Customer("小明",scanner.nextInt());
        Customer customer2 = new Customer("小军",scanner.nextInt());
        Customer customer3 = new Customer("小红",scanner.nextInt());
        List<Customer> customers = new ArrayList<>();
        customers.add(customer1);
        customers.add(customer2);
        customers.add(customer3);

        //write your code here......
        //调用排序接口
        Collections.sort(customers);
        
         System.out.println(customers);
    }
}

class Customer implements Comparable<Customer>{
    private String name;
    private int consumption;

    public Customer(String name, int consumption) {
        this.name = name;
        this.consumption = consumption;
    }

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

    //write your code here......
    @Override
    public int compareTo(Customer c){   // 自然排序,就是让元素所属的类实现 Comparable接口,重写compareTo(T o)方法
        int num = c.consumption - this.consumption; // 按照消费值从大到小排序
        return num;
    }

}

全部评论

相关推荐

点赞 评论 收藏
分享
牛客928043833号:在他心里你已经是他的员工了
点赞 评论 收藏
分享
06-11 13:34
门头沟学院 C++
offe从四面八方来:我真的没时间陪你闹了
点赞 评论 收藏
分享
面试官问:为什么不考研?该怎么回答啊😭我说现在的就业环境差到底了,还有就是我不想学数学,感觉面试官笑容都凝固了😢
DayDayNoBug的鲜芋球:我说的是“上学期其实尝试过去探索一些研究的方向,但感觉那些对我来说都没有很大的吸引力,相比起研究我可能更喜欢开发这种实践性的东西,它会让我觉得很有意思并且会为之深入进去”(虽然也不知这个回答怎么样哈哈哈哈哈哈)
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务