重写compareTo()方法并不像它应该的那样工作

时间:2014-04-15 17:18:02

标签: java sorting

我根据surname的字母顺序排序对象列表时遇到问题: 我上课了:

public class Osoba implements Comparable<Osoba>
{
    private String name;
    private String surname;
    private String nip;
    private kraj country;

    public Osoba(String name, String surname, String nip, kraj country)
    {
        this.name = name;
        this.surname = surname;
        this.nip = nip;
        this.country = country;
    }

    @Override
    public int compareTo(Osoba o)
    {
        String tocompare = o.getsurname();
        if (this.surname.equalsIgnoreCase(tocompare))
        {
            return 0;
        }
        else
        {
            if (this.surname.compareTo(tocompare) == -1)
            {
                return -1;
            } else
            {
                return 1;
            }
        }
    }

    @Override
    public String toString()
    {
       return this.nip +  " " +this.surname+ " " + this.name;
    }

    public String getsurname()
    {
        return surname;
    }

}

然后我有了随机生成的人员列表。我调用了Collection.sort(myList),但它没有对我的列表进行排序。我究竟做错了什么? 例如:

6438088470 Mcpherson Jemima
4728926902 Mcpherson Neville
8093413641 Ballard Neville
8485620409 Mcpherson Neville
6118892423 Ballard Fallon
3110453986 Ballard Sybill
3338278297 Mcpherson Sybill
2797735926 Mcpherson Todd
7473716746 Mcpherson Evelyn
9519145537 Mcpherson Ima
After sorting:
6438088470 Mcpherson Jemima
4728926902 Mcpherson Neville
8093413641 Ballard Neville
8485620409 Mcpherson Neville
6118892423 Ballard Fallon
3110453986 Ballard Sybill
3338278297 Mcpherson Sybill
2797735926 Mcpherson Todd
7473716746 Mcpherson Evelyn
9519145537 Mcpherson Ima

2 个答案:

答案 0 :(得分:3)

根据Comparable的文档,compareTo会返回:

  

作为此对象的负整数,零或正整数   小于,等于或大于指定的对象。

因此,如果a 小于 b发生在之前,按自然顺序排序),a.compareTo(b)返回 负数 ,但不一定是-1

更改

if (this.surname.compareTo(tocompare) == -1)

if (this.surname.compareTo(tocompare) < 0)

你应该好。

修改
注意: 编写此代码的更好,更简单的方法是

@Override
public int compareTo(Osoba o)
{
    return this.surname.compareToIgnoreCase(tocompare.getsurname()));
}

答案 1 :(得分:0)

String.compareTo返回零以上和零以下的所有整个int值。因此,您的代码应如下所示:

@Override
public int compareTo(Osoba o)
{
    if (!this.surname.equalsIgnoreCase(o.getSurname()))
    {
        return this.surname.compareToIngoreCase(o.getSurname());
    }
    else
    {
        return this.name.compareToIngoreCase(o.getName());
    }
}