1. Pengenalan
Membandingkan objek adalah ciri penting bahasa pengaturcaraan berorientasikan objek.
Dalam tutorial ini, kita akan melihat beberapa ciri bahasa Java yang memungkinkan kita membandingkan objek. Selain itu, kita akan melihat ciri-ciri tersebut di perpustakaan luaran.
2. == dan ! = Pengendali
Mari kita mulakan dengan operator == dan ! = Yang dapat mengetahui sama ada dua objek Java sama atau tidak.
2.1. Primitif
Untuk jenis primitif, menjadi sama bermaksud mempunyai nilai yang sama:
assertThat(1 == 1).isTrue();
Terima kasih kepada penyahkotakan secara automatik, ini juga berfungsi ketika membandingkan nilai primitif dengan rakan sejenisnya :
Integer a = new Integer(1); assertThat(1 == a).isTrue();
Jika dua integer mempunyai nilai-nilai yang berbeza, == operator akan kembali palsu , manakala ! = Operator akan kembali benar .
2.2. Objek
Katakan kita mahu membandingkan dua jenis pembungkus Integer dengan nilai yang sama:
Integer a = new Integer(1); Integer b = new Integer(1); assertThat(a == b).isFalse();
Dengan membandingkan dua objek, nilai objek tersebut bukan 1. Sebaliknya alamat memori mereka di tumpukan berbeza kerana kedua-dua objek itu dibuat menggunakan operator baru . Sekiranya kita telah menetapkan a untuk b , maka kita akan mendapat hasil yang berbeza:
Integer a = new Integer(1); Integer b = a; assertThat(a == b).isTrue();
Sekarang, mari kita lihat apa yang berlaku apabila kita menggunakan kaedah kilang # valueOf Integer :
Integer a = Integer.valueOf(1); Integer b = Integer.valueOf(1); assertThat(a == b).isTrue();
Dalam kes ini, mereka dianggap sama. Ini kerana kaedah valueOf () menyimpan Integer dalam cache untuk mengelakkan membuat terlalu banyak objek pembungkus dengan nilai yang sama. Oleh itu, kaedah mengembalikan contoh Integer yang sama untuk kedua-dua panggilan.
Java juga melakukan ini untuk String :
assertThat("Hello!" == "Hello!").isTrue();
Namun, jika mereka dibuat menggunakan operator baru , maka mereka tidak akan sama.
Akhirnya, dua rujukan nol dianggap sama, sementara objek bukan nol akan dianggap berbeza dari nol :
assertThat(null == null).isTrue(); assertThat("Hello!" == null).isFalse();
Sudah tentu, tingkah laku pengendali persamaan boleh membataskan. Bagaimana jika kita mahu membandingkan dua objek yang dipetakan ke alamat yang berlainan dan masih dianggap sama berdasarkan keadaan dalamannya? Kita akan melihat bagaimana di bahagian seterusnya.
3. Objek # sama Kaedah
Sekarang, mari kita bincangkan konsep persamaan yang lebih luas dengan kaedah sama () .
Kaedah ini ditentukan dalam kelas Objek sehingga setiap objek Java mewarisinya. Secara lalai, pelaksanaannya membandingkan alamat memori objek, sehingga berfungsi sama seperti operator == . Walau bagaimanapun, kita boleh mengatasi kaedah ini untuk menentukan apa maksud persamaan untuk objek kita.
Pertama, mari kita lihat bagaimana kelakuannya untuk objek yang ada seperti Integer :
Integer a = new Integer(1); Integer b = new Integer(1); assertThat(a.equals(b)).isTrue();
Kaedah masih kembali benar apabila kedua-dua objek itu sama.
Kita harus perhatikan bahawa kita dapat melewati objek nol sebagai argumen kaedah, tetapi tentu saja, bukan sebagai objek yang kita sebut kaedah tersebut.
Kita boleh menggunakan kaedah sama () dengan objek kita sendiri. Katakan kita mempunyai kelas Person :
public class Person { private String firstName; private String lastName; public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } }
Kita boleh mengatasi kaedah sama dengan () untuk kelas ini sehingga kita dapat membandingkan dua Orang berdasarkan perincian dalaman mereka:
@Override public boolean equals(Object o) if (this == o) return true; if (o == null
Untuk maklumat lebih lanjut, lihat artikel kami mengenai topik ini.
4. Objek # sama dengan Kaedah Statik
Mari kita lihat Objek # sama dengan kaedah statik. Kami telah menyebutkan sebelumnya bahawa kami tidak dapat menggunakan null sebagai nilai objek pertama jika tidak, NullPointerException akan dilemparkan.
Yang sama dengan () kaedah yang Objek menyelesaikan kelas pembantu yang masalah. Ia memerlukan dua argumen dan membandingkannya, juga menangani nilai nol .
Mari bandingkan objek Person lagi dengan:
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();
Seperti yang kami katakan, kaedah ini menangani nilai nol . Oleh itu, jika kedua-dua argumen itu sia - sia, ia akan menjadi benar , dan jika hanya salah satu daripadanya tidak sah , ia akan menjadi salah .
Ini sangat berguna. Katakan kita mahu menambahkan tarikh lahir pilihan ke kelas Orang kita :
public Person(String firstName, String lastName, LocalDate birthDate) { this(firstName, lastName); this.birthDate = birthDate; }
Kemudian, kita harus mengemas kini kaedah sama dengan () tetapi dengan pengendalian nol . Kita boleh melakukannya dengan menambahkan syarat ini ke kaedah sama () :
birthDate == null ? that.birthDate == null : birthDate.equals(that.birthDate);
Walau bagaimanapun, jika kita menambah banyak medan yang tidak dapat ditolak ke kelas kita, ia boleh menjadi sangat tidak kemas. Menggunakan objek # sama dengan kaedah dalam kita sama dengan () pelaksanaan adalah lebih bersih, dan meningkatkan kebolehbacaan:
Objects.equals(birthDate, that.birthDate);
5. Antara Muka Berbanding
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
Dalam artikel ini, kami melihat berbagai cara untuk membandingkan objek di Jawa. Kami mengkaji perbezaan antara persamaan, persamaan, dan susunan. Kami juga melihat ciri-ciri yang sesuai di perpustakaan Apache Commons dan Jambu.
Seperti biasa, kod penuh untuk artikel ini boleh didapati di GitHub.