diff --git a/JavaDsaWithTest/src/main/java/org/practice/dsa/collections/ComparableDemo.java b/JavaDsaWithTest/src/main/java/org/practice/dsa/collections/ComparableDemo.java new file mode 100644 index 00000000..0d5c2a37 --- /dev/null +++ b/JavaDsaWithTest/src/main/java/org/practice/dsa/collections/ComparableDemo.java @@ -0,0 +1,45 @@ +package org.practice.dsa.collections; + +public class ComparableDemo implements Comparable { + 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 + "'}"; + } +} diff --git a/JavaDsaWithTest/src/main/java/org/practice/dsa/collections/ComparableExample.java b/JavaDsaWithTest/src/main/java/org/practice/dsa/collections/ComparableExample.java new file mode 100644 index 00000000..fdc0f209 --- /dev/null +++ b/JavaDsaWithTest/src/main/java/org/practice/dsa/collections/ComparableExample.java @@ -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 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); + } +} diff --git a/JavaDsaWithTest/src/main/java/org/practice/dsa/collections/ComparatorAndComparable.md b/JavaDsaWithTest/src/main/java/org/practice/dsa/collections/ComparatorAndComparable.md new file mode 100644 index 00000000..e71bff3a --- /dev/null +++ b/JavaDsaWithTest/src/main/java/org/practice/dsa/collections/ComparatorAndComparable.md @@ -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.