Commit d971cdd
committed
feat(ComparatorDemo4): add demo of custom Comparator reversing integer order
What
- Added custom comparator class My:
- Implements Comparator<Integer>.
- Overrides compare(Integer i1, Integer i2).
- Returns positive if i1 < i2, negative if i1 > i2, 0 if equal.
- Effectively reverses natural ordering (descending sort).
- Added ComparatorDemo4 class:
- Defines Integer array [2,4,6,8,1,3,5,7].
- Calls Arrays.sort(a, new My()) to sort using custom comparator.
- Prints sorted array.
Why
- Demonstrates how to override default natural ordering (ascending) by supplying custom comparator.
- Shows usage of Arrays.sort with a comparator.
- Educational example contrasting Comparable (default) vs Comparator (custom).
How
- Arrays.sort(a, new My()):
- Delegates element comparison to My.compare().
- Since My reverses the usual order, result is descending sort.
- Iterated through sorted array and printed elements.
Logic
- Input array: [2,4,6,8,1,3,5,7].
- My.compare(i1,i2):
- If i1 < i2 → return 1 → i1 placed after i2.
- If i1 > i2 → return -1 → i1 placed before i2.
- Output: [8,7,6,5,4,3,2,1].
- Edge cases:
- Equal integers → comparator returns 0 → order remains stable.
- Comparator must define total order; here logic is consistent with descending natural order.
- Complexity / performance: O(n log n) sorting.
- Concurrency / thread-safety: Not thread-safe; demo is safe with local array.
- Error handling: None needed.
Real-life applications
- Sorting numbers in descending order (leaderboards, scores, rankings).
- Custom ordering when natural order is not desired.
- Comparator is flexible: can sort by arbitrary criteria (length, priority, timestamps).
Notes
- Without passing new My(), Arrays.sort() uses natural ordering (Comparable).
- Comparator.comparingInt(i -> i).reversed() is a cleaner functional alternative.
- Demonstrates old-style comparator implementation via class; modern style often uses lambdas.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 8e5df9c commit d971cdd
File tree
1 file changed
+31
-0
lines changed- Section 25 Collections Frameworks/List Interface/ArrayList/Comparator/src
1 file changed
+31
-0
lines changedLines changed: 31 additions & 0 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
0 commit comments