题目的主要信息:
- 有三个客户对象,将三个客户对象存入集合中,并将其按照消费总额从高到低排序
具体做法:
排序部分我们调用Collections类的sort函数,sort函数可以对List进行排序,但是因为我们这是有姓名和消费总额的集合,无法直接排序,我们要在其类中重载比较方法,实现消费额大的在前小的在后。
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 +
'}';
}
public int compareTo(Customer other){ //重载比较方法
return other.consumption - this.consumption; //大的在前小的在后
}
}
复杂度分析:
- 时间复杂度:,三个对象,常数时间实现排序和输出
- 空间复杂度:,常数空间