gurpeet singh wrote:I would like to know internally which sort algorithm does Collections.sort() method uses ?
gurpeet singh wrote:thanks everyone. Yes helen i would like to know how to sort in descending order. I have understood the ascending scenario.
Dennis Deems wrote:
All you have to do is reverse the order in the compareTo method:
gurpeet singh wrote:when we say Obj1.compareTo(Obj2) does it mean that Obj2 is the next element in the collection/array ?
Matthew Brown wrote:
Dennis Deems wrote:
All you have to do is reverse the order in the compareTo method:
There are actually a couple of methods in java.util.Collections that will do that for you. One will return a Comparator that reverses the natural order, and the other can take any Comparator and will return another that works in reverse.
Dennis Deems wrote:This is true, but I think the poster's question is more about how it works than about what API he can call.
Matthew Brown wrote:
Dennis Deems wrote:This is true, but I think the poster's question is more about how it works than about what API he can call.
Maybe. But if you want to reverse an existing ordering, this is the best practice to use. It's less error prone, and better shows the intent of the code.
Imagine I've got a natural ordering that involves a number of different fields, and is quite complicated. Which is clearer - a fully implemented Comparator that reverses that logic, or Collections.reverseOrder()?
and POOF! You're gone! But look, this tiny ad is still here:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
|