按姓氏对对象数组进行排序 [英] sort array of objects by surname java

查看:125
本文介绍了按姓氏对对象数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被困在下面的这段代码中,我一直试图使用冒泡排序按姓氏对对象数组进行排序,然后将其打印出来.我在哪里出错,如何打印?这是我的代码

I am stuck on this following piece of code I have been trying to use a bubble sort to sort the array of objects by surname then print it out. where Am i going wrong and how can i print it out? here is my code

for(int i = 1; i < clipArray.length; i++) {
    for(int j = 0; j < clipArray.length; j++) {
        if(((clipArray[j].getSurname()).compareToIgnoreCase((clipArray[j+1].getSurname()))) {
            Clip temp = clipArray[j];
            clipArray[j] = clipArray[j+1];
            clipArray[j+1] = temp;
        }
    }
}

问题:必需的布尔值,位于int

problem: required boolean, found int

推荐答案

问题是

The problem is that String#compareToIgnoreCase returns an int and you require a boolean result for if statement. From its javadoc:

返回

指定的String大于,等于或小于此String时,为负整数,零或正整数,而忽略大小写考虑

a negative integer, zero, or a positive integer as the specified String is greater than, equal to, or less than this String, ignoring case considerations

因此,请根据定义将该方法的结果与另一个数字进行比较.

So, compare the result of this method with another number according to the definition.

if (clipArray[j].getSurname().compareToIgnoreCase(clipArray[j+1].getSurname()) < 0) {
    //...
}

此外,您的for循环声明中还有另一个错误.他们应该是这样的:

Also, you have another error in your for loop declarations. They should be like this:

for(int i = 1; i < clipArray.length; i++) {
    for(int j = 0; j < clipArray.length - 1; j++) { //spot the difference
        //...
    }
}

这篇关于按姓氏对对象数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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