2

我搜索了这个问题,但我只发现了一个令人困惑的线程,所以我将在这里询问我希望能得到更清晰的答案。

我有一个任务是使用 Comparable 接口按客户名称对数组中的对象进行排序。到目前为止,我只用整数完成了这个,所以我不确定如何将字符串比较在一起。我该怎么做呢?这是我到目前为止的位置,假设我要使用 a.name 与 this.name 相比:

public int comparedTo(Customer a)
{

}   //end comparedTo

我还需要创建一个类来实现 Comparator 接口,以根据客户购买对值进行排序,我认为我这样做是正确的,但我想确保在我把头发弄错之前,它是错误的。这是我为此所做的:

class NameComparator implements Comparator{
public int compare(Object cust1, Object cust2){    

    String cust1Purch = ((Customer)cust1).purchase;        
    String cust2Purch = ((Customer)cust2).purchase;

    return cust1Purch.compareTo(cust2Purch);
}

任何帮助是极大的赞赏!

4

5 回答 5

3

这是一个可能对您有所帮助的完整示例:

CustomerComparator

class CustomerComparator implements Comparator<Customer> {

    @Override
    public int compare(Customer c1, Customer c2) {
        return c1.name.compareTo(c2.name);   // or, simply c1.compareTo(c2);
    }
}

Comparable Customer

class Customer implements Comparable<Customer> {

    String name;

    public Customer(String name) {
        this.name = name;
    }

    @Override
    public int compareTo(Customer o) {
        return name.compareTo(o.name);
    }

    public String toString() {
        return name;
    }
}

一个简单的测试驱动程序:

public class Test {
    public static void main(String[] args) {

        List<Customer> customers = Arrays.asList(new Customer("Bravo"),
                                                 new Customer("Charlie"),
                                                 new Customer("Delta"),
                                                 new Customer("Alpha"));
        Collections.sort(customers);

        // Or
        // Collections.sort(customers, new CustomerComparator());

        System.out.println(customers);

    }
}

ideone.com 演示

于 2011-03-02T13:14:28.613 回答
3

一切正常,但您可以指定 Comparator 泛型类型,然后无需转换对象:

class NameComparator implements Comparator<Customer>{
public int compare(Customer cust1, Customer cust2){    

    String cust1Purch = cust1.purchase;        
    String cust2Purch = cust2.purchase;

    return cust1Purch.compareTo(cust2Purch);
}
于 2011-03-02T13:10:45.663 回答
0

我似乎得到了正确的Comparable界面。那里没什么复杂的。

至于Comparator,如果您不使用泛型,则还需要验证相同基类型的两个参数,至少Comparable因为您使用的是该接口:

if (cust1 instanceof Comparable && cust2 instanceof Comparable) {
   Comparable c1 = (Comparable) cust1;
   Comparable c2 = (Comparable) cust2;
   return c1.compareTo(c2);
} else {
   return false;
}
于 2011-03-02T13:12:09.717 回答
0

1)我会使用泛型来定义你的比较器并避免额外的类转换:

class NameComparator implements Comparator<Customer> {
    public int compare(Customer cust1, Customer cust2) {
      ...
    }
}

2)Java中的String类已经实现了Comparable接口(http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html)。因此,如果您只需要比较客户姓名或购买字符串,那么您可以将其委托给 String,这就是您已经在做的事情。

于 2011-03-02T13:12:17.077 回答
0

看起来不错。但是您可以使用泛型:

class NameComparator implements Comparator<Customer> {
    public int compare(Customer cust1, Customer cust2) {..}
}
于 2011-03-02T13:09:49.987 回答