How to implement common comparators in Java

Source: Internet
Author: User

In Java, it often involves the ordering of object arrays, which involves the comparison of objects.


The usual comparisons between objects can be seen in two ways:

The first aspect: whether the address of the object is the same, that is, whether to reference from the same object. This method can be done directly using "= =".

The second aspect: the comparison is made by the angle of one of the object's attributes.


For JDK8, there are three ways to implement object comparisons:

1. Overwrite the Equals () method of the object class;

2, inherit comparable interface, and implement CompareTo () method;

3, define a separate object comparator, inherit from the comparator interface, implement the Compare () method.

Depending on the sort method used, it is also different to choose which approach to implement the object's comparison.


The first method is easier to understand, and the copy Equals () method is generally used to sort the array of objects that are implemented by itself, whereas the latter two methods can be used when applying Java's built-in sorting algorithm.

Take a look at the second approach, which is to let the class you write inherit the comparable interface and implement the CompareTo () method of the interface, in which case you don't have to specify a specific comparer when using the Java.util.Arrays.sort () method, sort ( ) method to sort the objects using their own comparison functions. The specific instance code is as follows:

1 ImportJava.util.Arrays;2 3 classBookcookImplementscomparable<bookcook>{4 PrivateString title;5 Private DoublePrice6  PublicBookcook (String title,DoublePrice) {7  This. title = title;8  This. Price = Price;9}Ten@Override One  PublicString toString () { A return"Title:"+ This. Title+ ", Price:"+ This. Price; -} -@Override the  Public intCompareTo (Bookcook o) { - if( This. Price > O.price) { - return1; -}Else if( This. Price < O.price) { + return-1; -}Else{ + return0; A} at} -}

The comparator interface has emerged from JDK1.8, which solves the problem of not having to change the previous code when it is necessary to refine the object's comparison functionality based on already developed code. In this case, we need to define an object comparer separately, inheriting the comparator interface. The specific implementation code is as follows:

1 classStudent {2 PrivateString name;3 Private DoubleScore;4  PublicStudent (String name,DoubleScore) {5  This. name = name;6  This. score = score;7}8  Public DoubleGetscore () {9 return  This. score;Ten} One@Override A  PublicString toString () { - return"Name:"+ This. name+ ", Score:"+ This. score; -} the  -} - classStudentcomparatorImplementscomparator<student> { -@Override +  Public intCompare (Student o1,student O2) { - if(O1.getscore () > O2.getscore ()) { + return1; A}Else if(O1.getscore () < O2.getscore ()) { at return-1; -}Else{ - return0; -} -} -} in  Public classTestcomparator { -  to  Public Static voidMain (string[] args) { +  -Student[] sts =Newstudent[]{ the NewStudent ("Xiao Dai", 60), * NewStudent ("Xiao Wang", 90), $ NewStudent ("Lao Wang", 80),Panax Notoginseng NewStudent ("Xiao Xuan", 95) -}; the              +Java.util.Arrays.sort (STS,NewStudentcomparator ()); ASystem.out.println (Java.util.Arrays.toString (STS)); the} +}

The above three kinds of situations, because of the different circumstances, choose different methods to solve the actual problem.

How to implement common comparators in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.