Thursday, January 23, 2025
HomeProgrammingJava Comparable Interface

Java Comparable Interface

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:

See also  How to center a button in CSS

Method:

java
int compareTo(T obj);
  • Returns a negative value if this is less than obj.
  • Returns 0 if equal.
  • Returns a positive value if greater.

Example:

java
class Student implements Comparable<Student> {
int age;
public int compareTo(Student s) {
return this.age - s.age;
}
}

Objects implementing Comparable can be sorted using Collections.sort() or Arrays.sort().

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x