How do I write a compareTo method which compares objects?
Asked Answered
N

9

29

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

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

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

Nidifugous answered 4/4, 2012 at 18:46 Comment(1)
If you could just say someString < someOtherString, there wouldn't be much need for compareTo...Position
T
24

This is the right way to compare strings:

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

This won't even compile:

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

Use if (this.getLastName().compareTo(s.getLastName()) < 0) instead.

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;
Tercet answered 4/4, 2012 at 18:48 Comment(3)
I agree with the way you structures the if statement. The first was giving errors.Febri
So, Does all compareTo( ), equals( ) and hashCode( ) uses ONLY primitives to do comparison, overriding equals and calculating hashCode? It cannot be done with a non-primitive type. Is my understanding right?Odyssey
Yes, you can't use '>', '<' and '==' for non-primitive types, if that was your question.Tercet
C
18

The compareTo method is described as follows:

Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

Let's say we would like to compare Jedis by their age:

class Jedi implements Comparable<Jedi> {

    private final String name;
    private final int age;
        //...
}

Then if our Jedi is older than the provided one, you must return a positive, if they are the same age, you return 0, and if our Jedi is younger you return a negative.

public int compareTo(Jedi jedi){
    return this.age > jedi.age ? 1 : this.age < jedi.age ? -1 : 0;
}

By implementing the compareTo method (coming from the Comparable interface) your are defining what is called a natural order. All sorting methods in JDK will use this ordering by default.

There are ocassions in which you may want to base your comparision in other objects, and not on a primitive type. For instance, copare Jedis based on their names. In this case, if the objects being compared already implement Comparable then you can do the comparison using its compareTo method.

public int compareTo(Jedi jedi){
    return this.name.compareTo(jedi.getName());
}

It would be simpler in this case.

Now, if you inted to use both name and age as the comparison criteria then you have to decide your oder of comparison, what has precedence. For instance, if two Jedis are named the same, then you can use their age to decide which goes first and which goes second.

public int compareTo(Jedi jedi){
    int result = this.name.compareTo(jedi.getName());
    if(result == 0){
        result = this.age > jedi.age ? 1 : this.age < jedi.age ? -1 : 0;
    }
    return result;
}

If you had an array of Jedis

Jedi[] jediAcademy = {new Jedi("Obiwan",80), new Jedi("Anakin", 30), ..}

All you have to do is to ask to the class java.util.Arrays to use its sort method.

Arrays.sort(jediAcademy);

This Arrays.sort method will use your compareTo method to sort the objects one by one.

Calumniation answered 4/4, 2012 at 18:56 Comment(1)
To add, you can choose whether to display order the list by ascending or descending order by interchanging the positions of -1, 1 as the return valuesInvasion
T
2

Listen to @milkplusvellocet, I'd recommend you to implement the Comparable interface to your class as well.

Just contributing to the answers of others:

String.compareTo() will tell you how different a string is from another.

e.g. System.out.println( "Test".compareTo("Tesu") ); will print -1 and System.out.println( "Test".compareTo("Tesa") ); will print 19

and nerdy and geeky one-line solution to this task would be:

return this.lastName.equals(s.getLastName()) ? this.lastName.compareTo(s.getLastName()) : this.firstName.compareTo(s.getFirstName());

Explanation:

this.lastName.equals(s.getLastName()) checks whether lastnames are the same or not this.lastName.compareTo(s.getLastName()) if yes, then returns comparison of last name. this.firstName.compareTo(s.getFirstName()) if not, returns the comparison of first name.

Thibodeau answered 4/4, 2012 at 19:4 Comment(0)
C
1

if (s.compareTo(t) > 0) will compare string s to string t and return the int value you want.

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

        // compare last names
        return  this.lastName.compareTo(s.getLastName());    
    }

Now just test for a positive negative return from the method as you would have normally.

Cheers

Cantal answered 4/4, 2012 at 18:50 Comment(0)
H
1

You're almost all the way there.

Your first few lines, comparing the last name, are right on track. The compareTo() method on string will return a negative number for a string in alphabetical order before, and a positive number for one in alphabetical order after.

Now, you just need to do the same thing for your first name and score.

In other words, if Last Name 1 == Last Name 2, go on a check your first name next. If the first name is the same, check your score next. (Think about nesting your if/then blocks.)

Hbeam answered 4/4, 2012 at 18:50 Comment(1)
So are you saying I don't need the code starting at if(studentcompare !=0) because the line above that is already returning the positive and negative numbers?Nidifugous
A
1

Consider using the Comparator interface described here which uses generics so you can avoid casting Object to Student.

As Eugene Retunsky said, your first part is the correct way to compare Strings. Also if the lastNames are equal I think you meant to compare firstNames, in which case just use compareTo in the same way.

Annalist answered 4/4, 2012 at 18:54 Comment(0)
S
0

A String is an object in Java.

you could compare like so,

if(this.lastName.compareTo(s.getLastName() == 0)//last names are the same
Sextan answered 4/4, 2012 at 18:51 Comment(0)
C
0

I wouldn't have an Object type parameter, no point in casting it to Student if we know it will always be type Student.

As for an explanation, "result == 0" will only occur when the last names are identical, at which point we compare the first names and return that value instead.

public int Compare(Object obj)
{       
    Student student = (Student) obj;
    int result = this.getLastName().compareTo( student.getLastName() );

    if ( result == 0 )
    {
        result = this.getFirstName().compareTo( student.getFirstName() );
    }

    return result;
}
Chiropodist answered 4/4, 2012 at 19:1 Comment(0)
C
0

If you using compare To method of the Comparable interface in any class. This can be used to arrange the string in Lexicographically.

public class Student() implements Comparable<Student>{

public int compareTo(Object obj){
if(this==obj){
    return 0;
}
if(obj!=null){
    String objName = ((Student)obj).getName();
    return this.name.comapreTo.(objName);
}
}
Contented answered 29/8, 2018 at 17:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.