JavaRush /Java Blog /Random EN /compareTo method
Author
Владимир Портянко
Java-разработчик at Playtika

compareTo method

Published in the Random EN group
To organize objects of the same type stored in an array or collection, Java developers came up with the Comparable. It declares only one method compareTo:
public interface Comparable<T> {
    public int compareTo(T o);
}
compareTo method - 1An interface Comparableis parameterized by the type of the object it accepts as a parameter to the method compareTo. In this case, we warn the compiler what types of objects we are going to compare. If the type identity condition is not met, we will receive an error ClassCastException. A method compareToin Java compares the calling object with the object passed as a parameter and returns an integer as a result of the comparison:
  • positive if the calling object is larger than the object passed as a parameter;
  • negative if the calling object is smaller than the object passed as a parameter;
  • null if the objects are equal.
Writing object comparison logic is the sole concern of the class developer and is determined by the desired results of ordering.

Why is compareTo method needed in Java?

A Java programmer very often has to deal with arrays and lists of objects. When working with large amounts of data, it is often convenient to store it in an organized or sorted form. Firstly, it speeds up working with the collection when searching for the necessary information, and secondly, organized data is visually better perceived.
compareTo method - 2
One of the simplest and most effective ways to sort an array of objects is the sort()class method Arrays, and a collection of objects in the form of a list is a similar class method Collections. To sort using these methods, the Java developers gave us the freedom to choose how to specify the sorting criteria: by implementing the interface Comparablein the class of objects we want to sort, or by using the Comparator. In the first case, sorting methods accept a set of objects in the form of an array or list:
sort(T[]array)//sorting массива
sort(List<T> list)// sorting списка
and in the second - plus another implementation of the interface Comparator:
sort(T[]array, Comparator <? super T> comparator)//sorting массива
sort(List<T> list, Comparator <? super T> comparator)// sorting списка
The interface Comparableis used when we want to set a natural (the most logical from our point of view) order of objects when sorting. It is also a way to “hardwire” the algorithm for comparing objects of this class at the design stage. For example, using the implementation of this interface, the criteria for natural ordering in the wrapper classes of the main primitive types are defined: , Byte, Character, Long, Integer, Short, Double, Float, Boolean. StringThis also means that these classes have an implemented method compareTothat we can use in the program if necessary. Let's look at an example of string comparison to see how this method is implemented in the class String.
String str1="Аарон";
        String str2="АAPOH";
        String str3="аарон";
        String str4="ААрон";
        String str5="аАрон";
        String str6="Берта";
        String str7="берта";
String[] allStr=new String[]{str1,str2,str3,str4, str5,str6, str7};
        Arrays.sort(allStr);
        for (String s:allStr){
            System.out.println(s);
        }
    }
If we execute this code in the method main, we will get the following result:
АAPOH
ААрон
Аарон
Берта
аАрон
аарон
берта
As you can see in the example in the class String, the method compareToarranges strings alphabetically, lexicographically, and case-sensitive. It is this order of string comparison that is defined by the developers of the class Stringas natural. For a simpler understanding of what lexicographical order is, it is enough to remember how words are arranged in language dictionaries. When comparing numbers, objects are ordered in ascending order. This comparison logic is embedded in the classes Byte, Character, Long, Integer, Shor, Double, Float.

Let's implement the comparison in our class

Let's look at an example of how you can build the ability to compare objects into your class. When implementing a comparetoJava method, we can specify one or more criteria for ordering objects, and also use methods comparetofrom the Stringand classes Integer. For example, for class objects Userwe set sorting by name, and in case of equal names, by age. Objects will be arranged in their natural order (as the value increases). Class User:
public class User  implements Comparable <User>{//добавляем возможность сравнивать an objectы User

    private String name;
    private Integer age;
    private String email;

    public User(String name, int age, String email) {
        this.name = name;
        this.age = age;
        this.email = email;
    }

    @Override
//реализуем метод compareTo интерфейса Comparable
    public int compareTo(User o) {

//используем метод compareTo из класса String для сравнения имен
        int result = this.name.compareTo(o.name);

//если имена одинаковые -  сравниваем возраст,
используя метод compareTo из класса Integer

        if (result == 0) {
            result = this.age.compareTo(o.age);
        }
        return result;
    }

    @Override
    public String toString() {
        return "{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", email='" + email + '\'' +
                '}';
    }
Let's test the operation of the method compareToimplemented in the class Userusing the sortclass method Collections:
public static void main(String[] args) {
    User user = new User("Andrey", 19, "andryha@mail.ru");
    User user2 = new User("Олег", 25, "oleg@mail.ru");
    User user3 = new User("Andrey", 24,"opr@google.com");
    User user4 = new User("Igor", 16, "igor@mail.ru");
    User user5 = new User("Andrey", 44,"stary@google.com");
    List<User> list = new ArrayList<>();

    list.add(user);
    list.add(user2);
    list.add(user3);
    list.add(user4);
    list.add(user5);

    System.out.println("-------до сортировки--------");
    for (User u : list) {
        System.out.println(u);
    }
    System.out.println("-------после сортировки-----");
    Collections.sort(list);
    for (User u : list) {
        System.out.println(u);
    }
}
 }
}
Result of the method main:
-------до сортировки--------
{name='Андрей',  age=19,  email='andryha@mail.ru'}
{name='Олег',    age=25,  email='oleg@mail.ru'}
{name='Андрей',  age=24,  email='opr@google.com'}
{name='Игорь',   age=16,  email='igor@mail.ru'}
{name='Андрей',  age=44,  email='stary@google.com'}
-------после сортировки-----
{name='Андрей',  age=19,  email='andryha@mail.ru'}
{name='Андрей',  age=24,  email='opr@google.com'}
{name='Андрей',  age=44,  email='stary@google.com'}
{name='Игорь',   age=16,  email='igor@mail.ru'}
{name='Олег',    age=25,  email='oleg@mail.ru'}
So, let's summarize. If you are a supporter of order in everything and want to arrange your objects in an array or list without unnecessary code, use the interface Comparable. The implementation of its compareTo method makes it quite easy to build in a mechanism for naturally ordering objects in your class. If you have to work with collections and arrays of objects of standard classes described in the Java library, use ready-made implementations compareToin these classes.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION