Skip to content

Commit

Permalink
feat: Add Comparable Example
Browse files Browse the repository at this point in the history
  • Loading branch information
VishwajeetVT committed Dec 13, 2024
1 parent 8bbcc04 commit ceab87d
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package org.practice.dsa.collections;

public class ComparableDemo implements Comparable<ComparableDemo> {
private int id;
private String name;

public ComparableDemo(int id, String name) {
this.id = id;
this.name = name;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public int compareTo(ComparableDemo o) {
// if (this.id > o.id) {
// return 1;
// }
// if (this.id < o.id) {
// return -1;
// }
// return 0;

return Integer.compare(this.id, o.id);
}

@Override
public String toString() {
return "Student{id=" + id + ", name='" + name + "'}";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package org.practice.dsa.collections;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class ComparableExample {
public static void main(String[] args) {
List<ComparableDemo> demo = new ArrayList<>();
demo.add(new ComparableDemo(3, "V"));
demo.add(new ComparableDemo(1, "B"));
demo.add(new ComparableDemo(2, "X"));

Collections.sort(demo);
demo.forEach(System.out::println);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Both Comparator and Comparable are used to save the custom sorting logic in Java.

## Comparable:
- Purpose: To define the natural ordering of objects of a class.
- Interface: Found in `java.lang`.
- Method: `int compareTo(T o);`
- Modifies Class: The class itself implement `Comparable` interface.

0 comments on commit ceab87d

Please sign in to comment.