如何编写比较对象的compareTo方法? [英] How do I write a compareTo method which compares objects?

查看:99
本文介绍了如何编写比较对象的compareTo方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习数组,基本上我有一个可以收集姓氏,名字和分数的数组.

I am learning about arrays, and basically I have an array that collects a last name, first name, and score.

我需要编写一个compareTo方法,该方法将比较姓氏和名字,以便可以从姓氏开始按字母顺序对列表进行排序,然后,如果两个人具有相同的姓氏,则将对其进行排序名字.

I need to write a compareTo method that will compare the last name and then the first name so the list could be sorted alphabetically starting with the last names, and then if two people have the same last name then it will sort the first name.

我很困惑,因为我书中的所有信息都是在比较数字,而不是对象和字符串.

I'm confused, because all of the information in my book is comparing numbers, not objects and Strings.

这是我到目前为止编码的内容.我知道这是错误的,但至少可以解释我认为自己在做什么:

Here is what I have coded so far. I know it's wrong but it at least explains what I think I'm doing:

public int compare(Object obj) // creating a method to compare 
{   
    Student s = (Student) obj; // creating a student object

    // I guess here I'm telling it to compare the last names?
    int studentCompare = this.lastName.compareTo(s.getLastName()); 

    if (studentCompare != 0)
        return studentCompare;
    else 
    {
        if (this.getLastName() < s.getLastName())
            return - 1;

        if (this.getLastName() > s.getLastName())
            return 1;
    }
    return 0;
}

我知道<>符号是错误的,但是就像我说的那样,我的书仅向您展示如何使用compareTo.

I know the < and > symbols are wrong, but like I said my book only shows you how to use the compareTo.

推荐答案

这是比较字符串的正确方法:

This is the right way to compare strings:

int studentCompare = this.lastName.compareTo(s.getLastName()); 

这甚至无法编译:

if (this.getLastName() < s.getLastName())

使用 if (this.getLastName().compareTo(s.getLastName()) < 0).

因此要比较拳头/姓氏顺序,您需要:

So to compare fist/last name order you need:

int d = getFirstName().compareTo(s.getFirstName());
if (d == 0)
    d = getLastName().compareTo(s.getLastName());
return d;

这篇关于如何编写比较对象的compareTo方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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