How do I write a compareTo method which compares objects?

how to write a compareto method in java
compareto java return values
compareto java int
java string comparator
compareto() method signature
how to call compareto method in java
java compareto null pointer exception
sorting using compareto method in java

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.

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;

Comparing Objects - OmarElGabry's Blog, for example if you are writing Employee object you probably want to implement Comparable interface and override compareTo() method to compare current  The CompareTo method is implemented by types whose values can be ordered or sorted. It is called automatically by methods of non-generic collection objects, such as Array.Sort, to order each member of the array.

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.

How to override compareTo method in Java , For example string1.compareTo("Just a String object") where string1 is a literal and it's value is compared with the string specified in the method argument. Lexical order is nothing but alphabetically order. compareTo method does a sequential comparison of letters in the string that have the same position. In this method, if the first string is always lexicographically higher than second string, it returns a positive number.

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.

Java String compareTo() Method with examples, Compare the various types of fields as follows: numeric primitive For example, List , Map and Set do not implement Comparable . As well An alternative to implementing Comparable is passing Comparator objects as parameters. Be aware  You can read more about comparisons and writing compareTo() here. You can usually only compare an object of any class to an instance of the same class. Writing an equals() method is notoriously difficult.

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.)

Java Practices->Implementing compareTo, If you try to sort a list whose elements do not implement Comparable The compareTo method compares the receiving object with the specified object and  Java String compareTo() Method with examples. The Java String compareTo() method is used for comparing two strings lexicographically. Each character of both the strings is converted into a Unicode value for comparison. If both the strings are equal then this method returns 0 else it returns positive or negative value.

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.

Object Ordering, All Java classes that have a natural ordering implement this (String, Double, BigInteger, ). compare(a, b), Comparator interface. Compares values of two objects. compareTo method should throws an exception if the passed object has incompatible type or null. Sorting Comparable Objects Till now, we have objects, plugged-in with comparison capability, without

Java: Comparing objects, Type Parameters: T - the type of objects that this object may be compared to the class's compareTo method is referred to as its natural comparison method. Using Comparable's compareTo to compare an object to the elements in an arraylist. I created an object Student using Comparable with getters/setters as well as a method that overrides compareTo. In a separate file an arraylist of objects is populated from a text file. Now I need to compare the values in the arraylist to another Student object.

Comparable (Java Platform SE 7 ), In this first example, we implement the Comparable interface in the Simpson class, The compareTo() method compares a given object or the current instance  The multiple comparators was only if you want different comparison methods that are not a function of the data itself - i.e. sometimes you want to compare by name, other times by age, etc. To compare by multiple fields at the same time, only one comparator would be necessary.

Sorting with Comparable and Comparator in Java, in Java? compareTo() method is used to perform natural sorting on string. Natural sorting means the sort order which applies on the object, e.g., lexical order for String, n. compareTo() is used for comparing two strings lexicographically. str – This method only accepts only one input String data type. In compareTo() method, two strings are compared lexicographically (dictionary order). The first string is the String object itself on which method is called. Second string is argument to method. This method does the string comparison based on the Unicode value of each character in the strings.

Comments
  • If you could just say someString < someOtherString, there wouldn't be much need for compareTo...
  • I agree with the way you structures the if statement. The first was giving errors.
  • 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?
  • Yes, you can't use '>', '<' and '==' for non-primitive types, if that was your question.
  • 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 values
  • 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?