使用可比接口比较字符串时 [英] Using the Comparable interface when comparing Strings

查看:137
本文介绍了使用可比接口比较字符串时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索了这个问题,但我只找到一个线程,这是一种混乱,所以我要问这里是什么我希望将是一个更清晰的答案。

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.

我有一个分配使用可比接口由客户名称的数组对象进行排序。我只用整数做到了这一点,到目前为止,所以我不知道如何串放在一起比较。我会如何呢?这里是我到目前为止,假设我用a.name相比this.name:

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:

public int comparedTo(Customer a)
{

}   //end comparedTo

我还需要一个类来实现Comparator接口根据客户的购买值进行排序,我想我做到了正常,但我想确保我出去剥去我的头发之前,当它是错的。这里是我做过什么为:

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:

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

任何帮助是极大AP preciated!

Any help is greatly appreciated!

推荐答案

它都可以,但您可以指定比较通用的类型,然后无需投对象:

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

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

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

    return cust1Purch.compareTo(cust2Purch);
}

这篇关于使用可比接口比较字符串时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆