0% found this document useful (0 votes)
2 views4 pages

Java Comparable Interface Guide

The document explains the implementation of the Comparable interface in Java to define the natural ordering of objects. It covers class declaration, the logic of the compareTo method, and provides a usage example for sorting a list of Student objects based on their roll numbers. The compareTo method returns negative, zero, or positive values to indicate the order of comparison.

Uploaded by

ayushjain26589
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views4 pages

Java Comparable Interface Guide

The document explains the implementation of the Comparable interface in Java to define the natural ordering of objects. It covers class declaration, the logic of the compareTo method, and provides a usage example for sorting a list of Student objects based on their roll numbers. The compareTo method returns negative, zero, or positive values to indicate the order of comparison.

Uploaded by

ayushjain26589
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Comparable: Implementation Example

In Java, the Comparable interface is used to define the natural ordering of objects.

We will cover:

1. Class Declaration

2. compareTo Logic

3. Usage Example
1. Class Declaration

To implement Comparable, a class must:

- Implement the Comparable<T> interface

- Override the compareTo(T o) method

Example:

class Student implements Comparable<Student> {

int rollNo;

String name;

Student(int rollNo, String name) {

[Link] = rollNo;

[Link] = name;

}
2. compareTo Logic

The compareTo method defines how objects are compared.

Example:

@Override

public int compareTo(Student s) {

return [Link] - [Link]; // ascending order

Return values:

- Negative: this < s

- Zero: this == s

- Positive: this > s


3. Usage Example

Usage in sorting:

List<Student> list = new ArrayList<>();

[Link](new Student(2, "Alice"));

[Link](new Student(1, "Bob"));

[Link](list);

for (Student s : list) {

[Link]([Link] + " " + [Link]);

You might also like