自学内容网 自学内容网

集合排序 题目

JAVA44 集合排序

描述

有三个客户对象,将三个客户对象存入集合中,并将其按照消费总额从高到低排序

输入描述:

三个整数,分别代表三个客户的消费值

输出描述:

根据消费额从高到低排序后的集合(输出部分预设代码已经给出,为保证输出格式请不要随意更改)

示例:

输入:234 456 789

输出:
[Customer{name='小红', consumption=789}, Customer{name='小军', consumption=456}, Customer{name='小明', consumption=234}]

 

分析:

​ 1.重写内置比较器。

​ 2.使用 Collections.sort()方法。

 

代码:

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 o) {

        return o.consumption-this.consumption;
    }

   


}


原文地址:https://blog.csdn.net/m0_57463864/article/details/140241322

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!