Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Comparable issue [duplicate]

Tags:

java

I want to sort objects by a string they have. Just wondering does this make sense? Before now I have only used Arrays.sort(BlahList); But now I could have many objects and not just an arraylist of strings.

public class Contact implements Comparable
{
    private string name;

    public compareTo (Contact Contact1)
    {
        return this.name.compareTo(Contact1.name);
    }
}

and in the main method I have:

Collections.sort(ContactList);

I would also like to know if this would work for integers if the name was age?

like image 586
Andrea Avatar asked Mar 19 '26 11:03

Andrea


1 Answers

Firstly, you should type the Comparable interface:

public class Contact implements Comparable<Contact>

Secondly, you should use leading lowercase for your parameters/variables:

public compareTo (Contact contact)

Thirdly, prefer not using this. unless necessary - it's just code clutter:

return name.compareTo(contact.name);

And finally, yes, you can compare age like this:

return age - contact.age; // order youngest to oldest

Or the cleaner way (thanks for pointing this out JB):

return Integer.compareTo(age, contact.age);

This whole class should look like this:

public class Contact implements Comparable<Contact> {
    private string name;

    public int compareTo(Contact contact) {
        return name.compareTo(contact.name);
    }
}

Note: You were missing the return type int from the code for your compareTo() method.

To compare age instead, replace the compareTo() method with this:

public int compareTo(Contact contact) {
    return Integer.compareTo(age, contact.age);
}
like image 52
Bohemian Avatar answered Mar 26 '26 15:03

Bohemian