我的比较器的比较方法不起作用

问题描述 投票:0回答:1

我有一个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比较(客户customer_1,客户customer_2)。

坦白地讲,我不知道它用作比较器的用途;有谁知道如何解决此问题并按姓氏对其进行排序?

哦,一旦它能退货,如何将采购商品中的100(0-99)件变成退货清单中的103(0-102)件商品?不知道那是怎么回事。

修复了这一部分,我切换了for循环,读取Purchase,然后遍历所有客户的列表并找到匹配项,而不是Vise。

感谢您的任何帮助。

提前感谢。

我有一个Customer对象类,该类具有一些变量,并且已经在实现有关这些变量之一的Comparator。但是,我需要为另一个.... >>>

您没有使用compare方法。

    Collections.sort(customers);

上面的行不是按照您的比较器,而是按照客户的自然顺序(由Customer.compareTo()定义的)对客户进行排序。相反,您可以这样做:

    Collections.sort(customers, this);

现在您的CompareByLastName将在排序中用作比较器。

几个助手:

  • 您在比较器类中使用sort方法的设计是非常规的。不过应该可以。
  • compare方法中,不需要if-else构造。以下简单得多的实现就足够了:

       return customer_1.getLastName().compareTo(customer_2.getLastName());
    
java sorting collections comparator
1个回答
0
投票

您没有使用compare方法。

© www.soinside.com 2019 - 2024. All rights reserved.