compareTo inward Java is inward the same league of equals() in addition to hashcode() in addition to used to implement natural lodge of object, compareTo is slightly unlike to compare() method of Comparator interface which is used to implement custom sorting order. I bring seen during java interviews that many Java programmers non able to correctly write or implement equals(), hashCode() and compareTo() method for mutual concern objects similar Order or Employee. Simple argue behind this is that they either non sympathize the concept good plenty or doesn't write this materials at all. I volition endeavor to fill upward that gap inward this Java tutorial in addition to volition encounter What is compareTo() method inward java, how to write compareTo in Java and things to yell upward patch implementing compareTo in Java.
What is compareTo() method inward Java
compareTo() method is defined inward interface java.lang.Comparable in addition to it is used to implement natural sorting on java classes. natural sorting way the the form lodge which naturally applies on object e.g. lexical lodge for String, numeric lodge for Integer or Sorting employee yesteryear at that topographic point ID etc. nearly of the coffee inwardness classes including String in addition to Integer implements CompareTo() method in addition to supply natural sorting. Why practice y'all need CompareTo()
Comparator in addition to Comparable inward Java. Since nosotros shop coffee objects inward Collection at that topographic point are also surely Set and Map which provides automating sorting when y'all insert chemical ingredient on that e.g. TreeSet in addition to TreeMap. to implement sorting y'all need to override either compareTo(Object o) method or Comparable shape or compare(Object o1, Object o2) method of Comparator class. Most of the classes implement Comparable to implement natural order. for illustration if y'all are writing Employee object y'all in all probability desire to implement Comparable interface in addition to override compareTo() method to compare electrical flow employee amongst other employee based on ID. So essentially y'all need to override compareTo() because y'all need to sort elements inward ArrayList or whatever other Collection.
How to implement compareTo inward Java
There are surely rules in addition to of import points to yell upward patch overriding compareTo method:
1) CompareTo method must render negative set out if electrical flow object is less than other object, positive set out if electrical flow object is greater than other object in addition to null if both objects are equal to each other.
2) CompareTo must survive inward consistent amongst equals method e.g. if 2 objects are equal via equals() , at that topographic point compareTo() must render zero otherwise if those objects are stored inward SortedSet or SortedMap they volition non acquit properly. Since SortedSet or SortedMap use compareTo() to cheque the object if 2 unequal object are returned equal yesteryear compareTo those volition non survive added into Set or Map if they are non using external Comparator. One illustration where compareTo is non consistent amongst equals inward JDK is BigDecimal class. 2 BigDecimal set out for which compareTo returns zero, equals returns imitation equally clear from next BigDecimal comparing example:
BigDecimal bd1 = new BigDecimal("2.0");
BigDecimal bd2 = new BigDecimal("2.00");
System.out.println("comparing BigDecimal using equals: " + bd1.equals(bd2));
System.out.println("comparing BigDecimal using compareTo: " + bd1.compareTo(bd2));
Output:
comparing BigDecimal using equals: false
comparing BigDecimal using compareTo: 0
BigDecimal bd2 = new BigDecimal("2.00");
System.out.println("comparing BigDecimal using equals: " + bd1.equals(bd2));
System.out.println("comparing BigDecimal using compareTo: " + bd1.compareTo(bd2));
Output:
comparing BigDecimal using equals: false
comparing BigDecimal using compareTo: 0
How does it touching BigDecimal ? good if y'all shop these 2 BigDecimal inward HashSet y'all volition destination upward amongst duplicates (violation of Set Contract) i.e. 2 elements patch if y'all shop them inward TreeSet y'all volition destination upward amongst only 1 chemical ingredient because HashSet uses equals to cheque duplicates patch TreeSet uses compareTo to cheque duplicates. That's why its suggested to operate on compareTo consistent amongst equals method inward java.
3) CompareTo() must throw NullPointerException if electrical flow object instruct compared to null object equally opposed to equals() which render imitation on such scenario.
4) Another of import quest to Federal Reserve annotation is don't role subtraction for comparing integral values because upshot of subtraction tin overflow equally every int functioning inward Java is modulo 2^32. role either Integer.compareTo() or logical operators for comparison. There is 1 scenario where y'all tin role subtraction to cut down clutter in addition to amend performance. As nosotros know compareTo doesn't tending magnitude, it only tending whether upshot is positive or negative. While comparing 2 integral fields y'all tin role subtraction if y'all are absolutely surely that both operands are positive integer or to a greater extent than exactly at that topographic point unlike must survive less than Integer.MAX_VALUE. In this illustration at that topographic point volition survive no overflow in addition to your compareTo volition survive concise in addition to faster.
5. Use relational operator to compare integral numeric value i.e. < or > but role Float.compareTo() or Double.compareTo() to compare floating quest number equally relational operator doesn't obey contract of compareTo for floating quest numbers.
6. CompareTo() method is for comparing hence order inward which y'all compare 2 object matters. If y'all bring to a greater extent than than 1 pregnant plain to compare than ever start comparing from nearly pregnant field to to the lowest degree pregnant field. hither compareTo is unlike amongst equals because inward illustration of equality cheque lodge doesn't matter. similar inward higher upward example of compareTo if nosotros don't consider Id in addition to compare 2 pupil yesteryear its yell in addition to historic catamenia than yell should survive outset compare in addition to than age, hence if 2 pupil bring same yell 1 that has higher historic catamenia should upshot inward greater.
Student john12 = new Student(1001, "John", 12);
Student john13 = new Student(1002, "John", 13);
//compareTo volition render -1 equally historic catamenia of john12 is less than john13
System.out.println("comparing John, 12 in addition to John, xiii amongst compareTo :" + john12.compareTo(john13));
Output:
comparing John, 12 in addition to John, 13 amongst compareTo :-1
Student john13 = new Student(1002, "John", 13);
//compareTo volition render -1 equally historic catamenia of john12 is less than john13
System.out.println("comparing John, 12 in addition to John, xiii amongst compareTo :" + john12.compareTo(john13));
Output:
comparing John, 12 in addition to John, 13 amongst compareTo :-1
7. Another of import quest patch comparing String using compareTo is to consider case. only similar equals() doesn't consider case, compareTo also practice non consider case, if y'all desire to compare regardless of illustration than role String.compareToIgnoreCase() equally nosotros bring used inward higher upward example.
Where compareTo() method used inward Java
---------------------------------------------------
In Java API compareTo() method is used inward SortedSet e.g. TreeSet and SortedMap e.g. TreeMap for sorting elements on natural lodge if no explicit Comparator is passed to Collections.sort() method e.g.
as mentioned before if compareTo is non consistent amongst equals hence it could create foreign result. permit took approximately other illustration y'all set Stock Influenza A virus subtype H5N1 in addition to Stock B on StockSet which is a TreeSet. Both Stock Influenza A virus subtype H5N1 in addition to Stock B are equal yesteryear equals() method but compareTo render non null values for it which makes that StockB volition also survive landed into TreeSet which was voilation of Set itself because it is non supposed to allow duplicates.
Example of compareTo() inward Java
--------------------------------------
Let’s encounter an illustration of how to override compareTo method inward Java. This method is really similar to equals in addition to hashcode, telephone commutation thing is compareTo should supply natural ordering e.g. inward this illustration lodge of object based on Student ID.
public class Student implements Comparable {
private int id;
private String name;
private int age;
/*
*Compare a given Student amongst current(this) object.
*If electrical flow Student id is greater than the received object,
*then electrical flow object is greater than the other.
*/
public int compareTo(Student otherStudent) {
// render this.id - otherStudent.id ; //result of this functioning tin overflow
return (this.id < otherStudent.id ) ? -1: (this.id > otherStudent.id) ? 1:0 ;
}
}
private int id;
private String name;
private int age;
/*
*Compare a given Student amongst current(this) object.
*If electrical flow Student id is greater than the received object,
*then electrical flow object is greater than the other.
*/
public int compareTo(Student otherStudent) {
// render this.id - otherStudent.id ; //result of this functioning tin overflow
return (this.id < otherStudent.id ) ? -1: (this.id > otherStudent.id) ? 1:0 ;
}
}
here is approximately other illustration of compareTo method inward Java on which compareTo uses 2 pregnant plain to compare objects:
public class Student implements Comparable<Student> {
.....
/**
* Compare a given Student amongst current(this) object.
* outset compare yell in addition to than age
*/
@Override
public int compareTo(Student otherStudent) {
//compare name
int nameDiff = name.compareToIgnoreCase(otherStudent.name);
if(nameDiff != 0){
return nameDiff;
}
//names are equals compare age
return historic catamenia - otherStudent.age;
}
}
.....
/**
* Compare a given Student amongst current(this) object.
* outset compare yell in addition to than age
*/
@Override
public int compareTo(Student otherStudent) {
//compare name
int nameDiff = name.compareToIgnoreCase(otherStudent.name);
if(nameDiff != 0){
return nameDiff;
}
//names are equals compare age
return historic catamenia - otherStudent.age;
}
}
That’s all on implementing compareTo method inward Java. Please add together whatever other fact which y'all think of import to Federal Reserve annotation patch overriding compareTo. In summary compareTo should supply natural ordering in addition to compareTo must survive consistent amongst equals() method inward Java.
Further Learning
Complete Java Masterclass
How to Set ClassPath for Java inward Windows
How to Convert String to Date inward Java amongst Example