题解 | 集合排序

import java.util.*;

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......
    public String getName() {
        return name;
    }
    public int getConsumption() {
        return consumption;
    }
    @Override
    public int compareTo(Customer o) {
        return o.consumption - this.consumption;
    }

}

this.consumption - o.consumption:如果 this.consumption 大于 o.consumption,结果为正数。如果 this.consumption 等于 o.consumption,结果为零。如果 this.consumption 小于 o.consumption,结果为负数。

Collections.sort(customers); 调用了 Customer 类的 compareTo 方法来对 customers 列表进行排序。Collections.sort 方法会使用 Comparable 接口的 compareTo 方法来比较列表中的元素,并根据比较结果对列表进行排序。

@Override
public int compareTo(Customer o) {
    return o.consumption - this.consumption;
}
  • 这个方法定义了 Customer 对象之间的比较规则。
  • o.consumption - this.consumption 的结果决定了两个 Customer 对象的顺序:如果结果为正数,表示 o 的消费大于 this 的消费,o 应该排在 this 前面。如果结果为零,表示 o 和 this 的消费相同。如果结果为负数,表示 o 的消费小于 this 的消费,o 应该排在 this 后面。
  • 由于返回的是 o.consumption - this.consumption,这会导致列表按消费金额的降序排列。
Collections.sort(customers);
Collections.sort 方法会遍历 customers 列表中的每个 Customer 对象。
对于每一对 Customer 对象,Collections.sort 会调用它们的 compareTo 方法来比较它们的大小。
根据 compareTo 方法的返回值,Collections.sort 会调整列表中元素的顺序,最终实现降序排序。
  • Collections.sort 是一个通用的排序方法,用于对实现了 Comparable 接口的集合进行排序。
  • 它会调用集合中每个元素的 compareTo 方法来比较元素的大小,并根据比较结果对集合进行排序。
  • 在你的代码中,customers 是一个 List<Customer>,Customer 类实现了 Comparable<Customer> 接口,因此 Collections.sort 会使用 Customer 类的 compareTo 方法来排序。
@Override
public int compareTo(Customer o) {
    return this.consumption - o.consumption; // 升序排序
}

#牛客AI配图神器#

全部评论

相关推荐

xxxxOxo:该催就催,想要你的不会因为催就挂,催了就挂的是因为本来就要挂你
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务