Tuesday 6 September 2016

Java Comparable Interface and compareTo() Example

Hello, guys, today I am going to talk about one of the fundamental concepts in Java, defining the natural ordering of the objects e.g. lexicographical order for String and numerical order for Number classes e.g. Integer, Double, Float etc. The compareTo() method is defined in the java.lang.Comparable interface. It is used to define the natural ordering of an object e.g. String class override compareTo() to define the lexicographical order for String objects. Integer class override compareTo() to define the numeric ordering of integer objects. Similarly, you can override compareTo() method by implementing Comparable interface to define the natural order on which you want to order your object. For example, an Order should be ordered by order id hence compareTo() must provide logic for that.
Read more »

No comments:

Post a Comment