Java Comparable Interface
The Comparable
interface in Java is used to define the natural ordering of objects. It allows objects of a class to be compared to each other, enabling sorting. This interface is part of the java.lang
package and has a single method:
Method:
- Returns a negative value if
this
is less thanobj
. - Returns
0
if equal. - Returns a positive value if greater.
Example:
Objects implementing Comparable
can be sorted using Collections.sort()
or Arrays.sort()
.