Constructor method takes all the three parameters and stores them in an object of class Book.Book has three parameters, book_name, author, and year (year of book publication).It is generic, we can implement it with any type of object. The above class book, implements a Comparable interface.If a book is published after another book, it should return 1, if the book is released before another book it should return -1, and if both books are released in the same year, it should return 0. We compare two books by their publishing year. Let us define a simple class Book that implements a comparable interface, stores details like the name of the book, author, etc., in its object, and overrides the compareTo method. compareTo in java takes an object of this class as a parameter, and we can define this method to compare two objects according to the sorting order. Java Object compareTo(Object anotherObj)Īll the classes that implement the Comparable interface must override the compareTo method as it is a contract method of the interface. If string1 = string2, it returns 0 Three Variants of compareTo() Method in JavaĬompareTo methods are of three types, the one that takes an object as a parameter, the other takes String as a parameter, and the third performs String comparison ignoring case differences. If string1 < string2, it returns negative number If string1 > string2, it returns positive number Now the difference of Unicodes of Y Y Y and S S S is 6 6 6, so the output is 6.Īs we know character Y Y Y comes after S S S in the dictionary, it returns a positive number. Thus, it should return a positive number. Unicode of Y Y Y is 5 9 59 5 9 which is greater than S S S with Unicode 5 3 53 5 3. P, R, and I are equal in both the strings, the first non-matching character occurs at index 3 3 3. Let string1 = "PRIYA" and string2 = "PRISHA". Let us take two strings to understand how the compareTo method works internally. String1.charAt(i)-String2.charAt(i) In case, if String1 is greater than String2 compareTo in java will return a positive number, else if String2 is greater than String1, it will return a negative number and if both are equal it will return 0. If at any position characters are not same, it will return the difference in the Unicode (ASCII) of the first differing characters, i.e. If all the characters of strings are equal, it will return 0. If the characters of strings are equal, it will move to the next character of both the strings. It will compare each character one by one. It compares two Strings and returns a negative number, a positive number, or a zero. This method is used to compare two strings lexicographically. Any class implementing the Comparable interface must override the compareTo method. Java has an interface called Comparable, which contains the comapreTo() method. When we try comparing a null string with another non-empty string, we see that it throws NullPointerException.
0 Comments
Leave a Reply. |