Skip to content

Commit e0e870b

Browse files
committed
feat(ComparableDemo): add demo of natural ordering with Comparable
What - Added Student class in package Package2 implementing Comparable<Student>: - Fields: name, gpa. - Constructor to initialize fields. - compareTo(Student other): - Primary ordering: GPA descending (higher first). - Secondary ordering: name ascending (alphabetical). - toString() overridden for readable output. - Added ComparableDemo class: - Creates list of Student objects. - Sorts list using natural ordering (list.sort(null)). - Prints sorted students. - Creates list of Integer objects. - Sorts integers using their natural ordering (ascending). - Prints sorted numbers. Why - Demonstrates how Comparable defines a natural order for objects. - Shows how Collections can use natural ordering when sorting with null comparator. - Provides educational comparison between Student (custom natural order) and Integer (built-in natural order). How - Student implements Comparable and defines compareTo() logic. - In main(): - list.sort(null) sorts by Student’s compareTo() implementation. - numbers.sort(null) sorts by Integer’s natural order. - Printed results for both lists. Logic - Inputs: - Students: Charlie (3.5), Bob (3.7), Alice (3.5), Akshit (3.9). - Integers: [2, 1, 99]. - Outputs: - Students sorted by GPA descending, then name ascending: [Student{name='Akshit', gpa=3.9}, Student{name='Bob', gpa=3.7}, Student{name='Alice', gpa=3.5}, Student{name='Charlie', gpa=3.5}] - Integers sorted ascending: [1, 2, 99]. - Flow: 1. Define natural ordering in Student via compareTo. 2. Use sort(null) to rely on that natural ordering. 3. Print ordered collections. - Edge cases: - Equal GPA and equal name → considered equal by compareTo. - Complexity / performance: O(n log n) sorting. - Concurrency / thread-safety: Local lists; not thread-safe but safe in demo context. - Error handling: Not applicable. Real-life applications - Ranking students by GPA with consistent tiebreakers. - Comparable makes classes naturally sortable without requiring external comparators. - Useful in data structures like TreeSet or TreeMap that rely on natural ordering. Notes - Passing null to sort() explicitly signals to use natural ordering. - Comparator can still be supplied later for alternate orderings without modifying class. - Good practice: ensure compareTo is consistent with equals() for predictable behavior in sorted collections. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 542a790 commit e0e870b

File tree

1 file changed

+78
-0
lines changed
  • Section 25 Collections Frameworks/List Interface/ArrayList/Comparator/src/Package2

1 file changed

+78
-0
lines changed
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
package Package2;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
// Student class implements Comparable to define natural ordering of Student objects.
7+
class Student implements Comparable<Student> {
8+
9+
// Instance variables: hold the student's name and GPA.
10+
private String name;
11+
private double gpa;
12+
13+
// Constructor: initializes Student with a name and GPA.
14+
public Student(String name, double gpa) {
15+
this.name = name;
16+
this.gpa = gpa;
17+
}
18+
19+
/* The Comparable interface imposes a total ordering on the objects of the class.
20+
* - compareTo() defines the "natural ordering" of objects.
21+
* - Collections like List or TreeMap can use this ordering for sorting automatically.
22+
23+
* In this implementation:
24+
* - Students are compared primarily by GPA.
25+
* - Order is descending by GPA (higher GPA comes first).
26+
* - If GPAs are equal, comparison falls back to the student's name (ascending lexicographical order).
27+
*/
28+
29+
@Override
30+
public int compareTo(Student other) {
31+
// Compare by GPA (descending).
32+
int gpaComparison = Double.compare(other.gpa, this.gpa);
33+
if (gpaComparison != 0) {
34+
return gpaComparison;
35+
}
36+
// If GPA is the same, compare by name (ascending).
37+
return this.name.compareTo(other.name);
38+
}
39+
40+
// Override toString to provide a human-readable representation of the Student object.
41+
@Override
42+
public String toString() {
43+
return "Student{name='" + name + "', gpa=" + gpa + "}";
44+
}
45+
}
46+
47+
public class ComparableDemo {
48+
public static void main(String[] args) {
49+
50+
// Create a list of Student objects.
51+
List<Student> list = new ArrayList<>();
52+
list.add(new Student("Charlie", 3.5));
53+
list.add(new Student("Bob", 3.7));
54+
list.add(new Student("Alice", 3.5));
55+
list.add(new Student("Akshit", 3.9));
56+
57+
// Sort the list using natural ordering (defined in compareTo).
58+
// Passing `null` to sort() means "use the natural ordering."
59+
list.sort(null);
60+
System.out.println(list);
61+
62+
// Create a list of integers.
63+
List<Integer> numbers = new ArrayList<>();
64+
numbers.add(2);
65+
numbers.add(1);
66+
numbers.add(99);
67+
68+
// Sort integers in their natural ordering (ascending).
69+
numbers.sort(null);
70+
System.out.println(numbers);
71+
72+
/* NOTE:
73+
* - Comparable: Used when a class defines its own "natural order" by implementing compareTo().
74+
* - Comparator: Used for custom sorting logic, external to the class.
75+
* - In this example, Student implements Comparable, so we can sort Students naturally by GPA + name.
76+
*/
77+
}
78+
}

0 commit comments

Comments
 (0)