【发布时间】:2020-06-05 04:56:40
【问题描述】:
我有一个 Customer 对象类,它有一些变量,并且已经针对这些变量之一实现了 Comparator。但是我需要为不同的变量 last_name 实现另一个比较器。
由于我的 Customer 类中不能有 2 个 compareTo() 方法,所以我决定在这里专门为此创建一个 Comparing 类
public class CompareByLastName implements Comparator<Customer> {
private List<Purchase> purchases;
private List<Customer> customers;
public CompareByLastName(List<Purchase> purchases, List<Customer> customers) {
this.purchases = purchases;
this.customers = customers;
}
/**
* @param descending
* @return will be a sorted, in ascending, or descending, array of customer's according to their authors.
*/
public List<Purchase> sortByLastName(boolean descending){
List<Purchase> return_List = new LinkedList<Purchase>();
Collections.sort(customers);
if(descending == true) {
Collections.reverse(customers);
}
for(Customer customer : customers) {
for(Purchase purchase_info : purchases) {
if(customer.getId() == purchase_info.getCustomer_id()) {
return_List.add(purchase_info);
}
}
}
return return_List;
}
@Override
public int compare(Customer customer_1, Customer customer_2) {
int result = customer_1.getLastName().compareTo(customer_2.getLastName());
if(result < 0) {
return -1;
}
else if(result > 0) {
return 1;
}
else {
return 0;
}
}
}
但一旦点击 Collections.sort(customers);
它不会激活下面的公共 int compare(Customer customer_1, Customer customer_2)。
坦率地说,我不知道它在排序中用作比较器的是什么;有谁知道如何解决这个问题并按姓氏排序?
哦,一旦退货,如何设法从购买的 100(0-99) 件商品变为退货清单中的 103(0-102) 件商品?不知道这是怎么回事。
修复了这部分,我将 for 循环切换为“购买”,然后遍历所有客户的列表并找到匹配项,而不是反之亦然。
感谢任何帮助。
提前致谢。
【问题讨论】:
-
您的比较器的
compare方法不起作用,因为您没有将比较器的实例传递给Collections.sort。
标签: java sorting collections comparator