Contents
What is the required method of the Comparable interface?
compareTo method
If a class implements the Comparable interface, objects created from that class can be sorted using Java’s sorting algorithms. The compareTo method required by the Comparable interface receives as its parameter the object to which the “this” object is compared.
Can you instantiate an interface?
An interface can’t be instantiated directly. Its members are implemented by any class or struct that implements the interface. A class or struct can implement multiple interfaces. A class can inherit a base class and also implement one or more interfaces.
How to implement a comparable interface in Java?
As explained above, we can implement the Comparable interface in Java by having a custom class to implement the Comparable interface. The Comparable interface has only one method ‘compareTo’ which has to be overridden in the class to sort the custom objects.
How to sort custom objects using comparable interface?
Before we see how to sort an objects of custom objects, lets see how we can sort elements of arrays and Wrapper classes that already implements Comparable. In the above example, you have seen that how easy it is to sort the Arrays and list of objects that implements Comparable interface, you just need to call the Collections.sort (and Arrays.sort).
Which is public interface imposes total ordering on an object?
Interface Comparable . public interface Comparable This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class’s natural ordering, and the class’s compareTo method is referred to as its natural comparison method.
When to use public int compareTo in Java?
For example, it may be rollno, name, age or anything else. public int compareTo (Object obj): It is used to compare the current object with the specified object. It returns positive integer, if the current object is greater than the specified object.