Сравняване на обекти в Java

1. Въведение

Сравняването на обекти е съществена характеристика на обектно-ориентираните програмни езици.

В този урок ще разгледаме някои от характеристиките на езика Java, които ни позволяват да сравняваме обекти. Освен това ще разгледаме такива функции във външни библиотеки.

2. == и ! = Оператори

Нека започнем с операторите == и ! =, Които могат да разберат дали два Java обекта са еднакви или не съответно.

2.1. Примитиви

За примитивните типове да бъдеш еднакъв означава да имаш равни стойности:

assertThat(1 == 1).isTrue();

Благодарение на автоматичното разопаковане, това работи и при сравняване на примитивна стойност с нейния аналог от типа обвивка :

Integer a = new Integer(1); assertThat(1 == a).isTrue();

Ако две цели числа имат различни стойности, операторът == ще върне false , докато операторът ! = Ще върне true .

2.2. Обекти

Да предположим, че искаме да сравним два типа обвивки Integer със същата стойност:

Integer a = new Integer(1); Integer b = new Integer(1); assertThat(a == b).isFalse();

Като сравняваме два обекта, стойността на тези обекти не е 1. По-скоро адресите на паметта им в стека са различни, тъй като и двата обекта са създадени с помощта на новия оператор. Ако бяхме задали a на b , тогава щяхме да имаме различен резултат:

Integer a = new Integer(1); Integer b = a; assertThat(a == b).isTrue();

Сега нека видим какво се случва, когато използваме фабричния метод Integer # valueOf :

Integer a = Integer.valueOf(1); Integer b = Integer.valueOf(1); assertThat(a == b).isTrue();

В този случай те се считат за еднакви. Това е така, защото методът valueOf () съхранява цялото число в кеш, за да се избегне създаването на твърде много обекти-обвивки със същата стойност. Следователно методът връща един и същ екземпляр Integer и за двете обаждания.

Java също прави това за String :

assertThat("Hello!" == "Hello!").isTrue();

Ако обаче са създадени с помощта на новия оператор, те няма да бъдат същите.

И накрая, две нулеви препратки се считат за еднакви, докато всеки ненулеви обект ще се счита за различен от null :

assertThat(null == null).isTrue(); assertThat("Hello!" == null).isFalse();

Разбира се, поведението на операторите за равенство може да бъде ограничаващо. Ами ако искаме да сравним два обекта, картографирани на различни адреси и въпреки това да ги считаме за равни въз основа на техните вътрешни състояния? Ще видим как в следващите раздели.

3. Обект # е равен на Метод

Сега, нека поговорим за по-широко понятие за равенство с метода equals () .

Този метод е дефиниран в клас Object, така че всеки Java обект го наследява. По подразбиране изпълнението му сравнява адресите на обектната памет, така че работи по същия начин като оператора == . Можем обаче да заменим този метод, за да определим какво означава равенството за нашите обекти.

Първо, нека видим как се държи за съществуващи обекти като Integer :

Integer a = new Integer(1); Integer b = new Integer(1); assertThat(a.equals(b)).isTrue();

Методът все пак връща true, когато и двата обекта са еднакви.

Трябва да отбележим, че можем да предадем нулев обект като аргумент на метода, но разбира се, не като обект, върху който извикваме метода.

Можем да използваме метода equals () със собствен обект. Да приемем, че имаме клас Person :

public class Person { private String firstName; private String lastName; public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } }

Можем да заменим метода equals () за този клас, за да можем да сравним две Person s въз основа на техните вътрешни подробности:

@Override public boolean equals(Object o)  if (this == o) return true; if (o == null 

За повече информация вижте нашата статия по тази тема.

4. Обекти # е равно на статичен метод

Нека сега разгледаме статичния метод Objects # equals . По-горе споменахме, че не можем да използваме нула като стойност на първия обект в противен случай NullPointerException ще бъдат изхвърлени.

Методът equals () на помощния клас Objects решава тези проблеми. Отнема два аргумента и ги сравнява, като също обработва нулеви стойности.

Нека отново сравним Person обекти с:

Person joe = new Person("Joe", "Portman"); Person joeAgain = new Person("Joe", "Portman"); Person natalie = new Person("Natalie", "Portman"); assertThat(Objects.equals(joe, joeAgain)).isTrue(); assertThat(Objects.equals(joe, natalie)).isFalse();

Както казахме, методът обработва нулеви стойности. Следователно, ако и двата аргумента са null, той ще върне true и ако само един от тях е null , ще върне false .

Това може да е много удобно. Да предположим, че искаме да добавим незадължителна дата на раждане към нашия клас Person :

public Person(String firstName, String lastName, LocalDate birthDate) { this(firstName, lastName); this.birthDate = birthDate; }

След това ще трябва да актуализираме метода equals () , но с нулева обработка. Можем да направим това, като добавим това условие към нашия метод equals () :

birthDate == null ? that.birthDate == null : birthDate.equals(that.birthDate);

Ако обаче добавим много полета, които могат да бъдат затривани към нашия клас, той може да стане наистина объркан. Използването на метода Objects # equals в нашата реализация equals () е много по-изчистен и подобрява четливостта:

Objects.equals(birthDate, that.birthDate);

5. Сравним интерфейс

Comparison logic can also be used to place objects in a specific order. The Comparable interface allows us to define an ordering between objects, by determining if an object is greater, equal, or lesser than another.

The Comparable interface is generic and has only one method, compareTo(), which takes an argument of the generic type and returns an int. The returned value is negative if this is lower than the argument, 0 if they are equal, and positive otherwise.

Let's say, in our Person class, we want to compare Person objects by their last name:

public class Person implements Comparable { //... @Override public int compareTo(Person o) { return this.lastName.compareTo(o.lastName); } }

The compareTo() method will return a negative int if called with a Person having a greater last name than this, zero if the same last name, and positive otherwise.

For more information, take a look at our article about this topic.

6. Comparator Interface

The Comparator interface is generic and has a compare method that takes two arguments of that generic type and returns an integer. We already saw that pattern earlier with the Comparable interface.

Comparator is similar; however, it's separated from the definition of the class. Therefore, we can define as many Comparators we want for a class, where we can only provide one Comparable implementation.

Let's imagine we have a web page displaying people in a table view, and we want to offer the user the possibility to sort them by first names rather than last names. It isn't possible with Comparable if we also want to keep our current implementation, but we could implement our own Comparators.

Let's create a PersonComparator that will compare them only by their first names:

Comparator compareByFirstNames = Comparator.comparing(Person::getFirstName);

Let's now sort a List of people using that Comparator:

Person joe = new Person("Joe", "Portman"); Person allan = new Person("Allan", "Dale"); List people = new ArrayList(); people.add(joe); people.add(allan); people.sort(compareByFirstNames); assertThat(people).containsExactly(allan, joe);

There are other methods on the Comparator interface we can use in our compareTo() implementation:

@Override public int compareTo(Person o) { return Comparator.comparing(Person::getLastName) .thenComparing(Person::getFirstName) .thenComparing(Person::getBirthDate, Comparator.nullsLast(Comparator.naturalOrder())) .compare(this, o); }

In this case, we are first comparing last names, then first names. Then, we compare birth dates but as they are nullable we must say how to handle that so we give a second argument telling they should be compared according to their natural order but with null values going last.

7. Apache Commons

Let's now take a look at the Apache Commons library. First of all, let's import the Maven dependency:

 org.apache.commons commons-lang3 3.10 

7.1. ObjectUtils#notEqual Method

First, let's talk about the ObjectUtils#notEqual method. It takes two Object arguments, to determine if they are not equal, according to their own equals() method implementation. It also handles null values.

Let's reuse our String examples:

String a = new String("Hello!"); String b = new String("Hello World!"); assertThat(ObjectUtils.notEqual(a, b)).isTrue(); 

It should be noted that ObjectUtils has an equals() method. However, that's deprecated since Java 7, when Objects#equals appeared

7.2. ObjectUtils#compare Method

Now, let's compare object order with the ObjectUtils#compare method. It's a generic method that takes two Comparable arguments of that generic type and returns an Integer.

Let's see that using Strings again:

String first = new String("Hello!"); String second = new String("How are you?"); assertThat(ObjectUtils.compare(first, second)).isNegative();

By default, the method handles null values by considering them as greater. It offers an overloaded version that offers to invert that behavior and consider them lesser, taking a boolean argument.

8. Guava

Now, let's take a look at Guava. First of all, let's import the dependency:

 com.google.guava guava 29.0-jre 

8.1. Objects#equal Method

Similar to the Apache Commons library, Google provides us with a method to determine if two objects are equal, Objects#equal. Though they have different implementations, they return the same results:

String a = new String("Hello!"); String b = new String("Hello!"); assertThat(Objects.equal(a, b)).isTrue();

Though it's not marked as deprecated, the JavaDoc of this method says that it should be considered as deprecated since Java 7 provides the Objects#equals method.

8.2. Comparison Methods

Now, the Guava library doesn't offer a method to compare two objects (we'll see in the next section what we can do to achieve that though), but it does provide us with methods to compare primitive values. Let's take the Ints helper class and see how its compare() method works:

assertThat(Ints.compare(1, 2)).isNegative();

As usual, it returns an integer that may be negative, zero, or positive if the first argument is lesser, equal, or greater than the second, respectively. Similar methods exist for all the primitive types, except for bytes.

8.3. ComparisonChain Class

Finally, the Guava library offers the ComparisonChain class that allows us to compare two objects through a chain of comparisons. We can easily compare two Person objects by the first and last names:

Person natalie = new Person("Natalie", "Portman"); Person joe = new Person("Joe", "Portman"); int comparisonResult = ComparisonChain.start() .compare(natalie.getLastName(), joe.getLastName()) .compare(natalie.getFirstName(), joe.getFirstName()) .result(); assertThat(comparisonResult).isPositive();

The underlying comparison is achieved using the compareTo() method, so the arguments passed to the compare() methods must either be primitives or Comparables.

9. Conclusion

В тази статия разгледахме различните начини за сравняване на обекти в Java. Проучихме разликата между еднаквост, равенство и подреденост. Разгледахме и съответните функции в библиотеките Apache Commons и Guava.

Както обикновено, пълният код за тази статия може да бъде намерен в GitHub.