Keeping CompareTo and equals synchronized for the Java collection

Source: Internet
Author: User
Tags comparable

In Java we often use the comparable interface to implement sorting, where CompareTo is implementing the interface method. We know that CompareTo returns 0 means that two objects are equal, a positive number represents greater than, and a negative number represents less than. At the same time we know that equals can also determine whether two objects are equal, then whether there is an association between them?

Public Class Student Implements Comparable<Student>{ Private StringId; Private StringName; Private IntAge; Public Student(StringId,StringName,IntAge){ This.Id=Id; This.Name=Name; This.Age=Age; } Public Booleanequals(ObjectObj){ If(Obj== Null){ Return False; } If(This ==Obj){ Return True; } If(Obj.GetClass() != This.GetClass()){ Return False; } StudentStudent= (Student)Obj; If(!Student.GetName().equals(GetName())){ Return False; } Return true;} public int  Compareto (student Student   { returnthis. Age - Student.; } /** Omit getter, setter method */}           

The student class implements the comparable interface and implements the Equals method, where CompareTo is compared according to age, and equals is based on name.

Public Static voidMain(String[]Args){ List<Student>List= New ArrayList<>();List.Add(New Student("1", "Chenssy1", 24));List.Add(New Student("2", "Chenssy1", 26)); Collections.Sort(List); //Sort StudentStudent= New Student("2", "Chenssy1", 26); //Retrieving the position of a student in a list IntIndex1=List.IndexOf(Student); IntIndex2= collections. (list, student  system.. Println ( "INDEX1 ="  + Index1 system.. Println ( "INDEX2 ="  + Index2 }            /span>                

According to conventional thinking, both index should be consistent, because they are retrieving the same object, but unfortunately, the result of its operation:

=0=1  

Why does it produce such a different result? This is because the implementation mechanism of indexof and BinarySearch is different, indexof is based on equals, so long as equals returns True, it is assumed that the same element has been found. The BinarySearch is based on the CompareTo method, and when CompareTo returns 0 o'clock it is assumed that the element has been found. In our implementation of the student class we overwrite the CompareTo and equals methods, but our CompareTo and equals are based on different, one is age and one is based on name. The results obtained by comparison are likely to be different. So knowing the reason, we are good to modify: the comparison between the two to maintain consistency.

For the CompareTo and equals two methods we can conclude that: CompareTo is to determine whether the position of the elements in the sorting is equal, equals is to determine whether the elements are equal, since a decision to sort the position, a decision is equal, so we very need to ensure that when the sorting position is the same, Its equals should also be equal.

Details: Implementing the CompareTo method makes it necessary to implement the Equals method, while also ensuring that two methods are synchronized.

This article was reproduced from: http://cmsblogs.com/?p=1242

Keep CompareTo and equals synchronization for Java collections

Related Article

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.