Skip to content

Instantly share code, notes, and snippets.

@Rohit-554
Created March 25, 2023 18:48
Show Gist options
  • Select an option

  • Save Rohit-554/73d3d8c4ad431d52315e4d860bc613c0 to your computer and use it in GitHub Desktop.

Select an option

Save Rohit-554/73d3d8c4ad431d52315e4d860bc613c0 to your computer and use it in GitHub Desktop.
This is comparables, this interfaces compares different objects of the class based on the type of object we give, like in this case age
import java.util.*;;
public class comparable implements Comparable<comparable> {
private String name;
private int age;
public comparable(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(comparable otherPerson) {
return this.age - otherPerson.age;
// return this.name.compareTo(otherPerson.name);
}
public String toString() {
return name + " (" + age + ")";
}
public static void main(String[] args) {
List<comparable> people = new ArrayList<>();
people.add(new comparable("Alice", 25));
people.add(new comparable("Bob", 20));
people.add(new comparable("Charlie", 30));
Collections.sort(people);
for (int i = 0; i < people.size(); i++) {
comparable p = people.get(i);
System.out.println(p);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment