题意整理。
- 给定三个客户对象,存入集合中。
- 按照消费总额从高到低排序。
方法一(重写compareTo方法)
1.解题思路
- 由于Collections没有提供适用于客户对象的排序实现,要想对其进行排序,需要实现Comparable接口,重写compareTo方法。
- 在compareTo方法中,按照客户总额从高到低排序。
图解展示:
2.代码实现
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);
//调用排序接口
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 +
'}';
}
//重写compareTo()方法,按照消费额从高到低排序
@Override
public int compareTo(Customer c){
return c.consumption-consumption;
}
}
3.复杂度分析
- 时间复杂度:只有3个客户需要进行排序,所以时间复杂度为O(1)。
- 空间复杂度:需要额外常数级别的空间,所以空间复杂度为O(1)。