java 比较字符串时使用 Comparable 接口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5167868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:47:29  来源:igfitidea点击:

Using the Comparable interface when comparing Strings

javaarraysinterfacecomparatorcomparable

提问by Lish

I searched for this question, but I only found one thread that was kind of confusing, so I'm going to ask here for what I hope will be a clearer answer.

我搜索了这个问题,但我只找到了一个令人困惑的话题,所以我要在这里问一下,我希望得到一个更清晰的答案。

I have an assignment to use the Comparable interface to sort objects in an array by customer name. I have only done this with integers so far, so I'm not sure how to compare the strings together. How would I go about that? Here is where I am so far, assuming I am to use a.name compared to this.name:

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

public int comparedTo(Customer a)
{

}   //end comparedTo

I also need to make a class to implement the Comparator interface to sort the values based on customer purchases and I think I did that properly, but I'd like to make sure before I go ripping my hair out when it's wrong. Here is what I did for that:

我还需要创建一个类来实现 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);
}

Any help is greatly appreciated!

任何帮助是极大的赞赏!

回答by Sergey Vedernikov

Its all ok, but you can specify Comparator generic type and then no need to cast objects:

一切正常,但您可以指定 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);
}

回答by aioobe

Here is a complete example that might help you:

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

A CustomerComparator:

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);
    }
}

A ComparableCustomer:

ComparableCustomer

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;
    }
}

A simple test driver:

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

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)

ideone.com 演示

回答by Bozho

Looks fine. But you can utilize Generics:

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

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

回答by Yanick Rochon

I seem to get it right for the Comparableinterface. Nothing really complicated there.

我似乎很适合Comparable界面。没有什么真正复杂的。

As for the Comparator, if you're not using generics, you also need to validate both argument for the same base type, at least Comparablesince you're using that interface :

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

if (cust1 instanceof Comparable && cust2 instanceof Comparable) {
   Comparable c1 = (Comparable) cust1;
   Comparable c2 = (Comparable) cust2;
   return c1.compareTo(c2);
} else {
   return false;
}

回答by Andrey Adamovich

1) I would use generics to define your comparator and avoid additinal class casting:

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

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

2) String class in java already implements Comparable interface ( http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html). So, if you need to just compare on customer's name or purchase string, then you can just delegate it to String and that's what you already do.

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