

The natural ordering should be by lName, fName, middleInitial. My object has three fields that make up a name. Inside the overridden compareTo () method, we compare the age of the person object that is passed with that of the current object and accordingly return the value.Īn Example Java program is given below.I'm implementing the compareTo method to set the natural order of an object.

Note that as we are going to sort custom objects, we need to override the ‘compareTo ()’ method of the Comparable interface. It returns one integer value based on the comparison. This argument string is compared with the caller string. Next, ensure that you return the correct data type from a method.
Compareto method map java code#
This will help to ensure that your code is reliable and easy to debug. This includes returning void if there’s nothing to return. First, return a value from a method whenever possible. Similar to the above method, it compares two strings lexicographically. When it comes to the Java return keyword, there are a few best practices to keep in mind. This class implements a ‘Comparable’ interface that will allow us to sort the object of class Person. public int compareTo(String anotherString) This is a public method in the String class. The following Java program implements a Person class that contains name and age as member fields. Now let’s implement an example of a Comparable interface. Java - String compareTo() Method, This Java tutorial covers basic to advanced concepts related to Java Programming including What is Java, Java Environment Setup, Java Objects and Classes, Datatypes, Variable Types, Modifiers, Operators, Loops, Decision Making Statements, Date, Time, Regular Expressions, Files. We can use the compareTo () method to sort:
public int compareTo(Boolean b) Specified by.

Following is the declaration for () method. Once the list objects implement Comparable interface, we can then use the Collections.sort () method or Arrays.sort () in case of the arrays to sort the contents.īut when we have custom classes and we need to sort their objects, then we will have to implement the Comparable interface in this class. The (Boolean b) compares this Boolean instance with another.
