比较字符串时使用Comparable接口

时间:2011-03-02 13:05:38

标签: java arrays interface comparator comparable

我搜索了这个问题,但我只发现了一个令人困惑的帖子,所以我想在这里问一下我希望能得到更明确的答案。

我有一个使用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);
}

非常感谢任何帮助!

5 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:3)

以下是一个可以帮助您的完整示例:

A 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 demo

答案 2 :(得分:0)

看起来很好。但你可以使用泛型:

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

答案 3 :(得分: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;
}

答案 4 :(得分: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,这就是您已经做过的事情。