I was so confused about comparator and Collections.sort() in Java. I don't understand the order induced by the comparator. I don't clear about which number the compare function should return to get the sorting direction. I also don't know how Collections will use that compare result to sort the input data. Should I learn them by heart? Is there anything easier to understand them? Can anybody explain it for me? Thanks.
public int compare(Obj a, Obj b){
if(a.age > b.age) return 1;
if(a.age < b.age) return -1;
else return 0;
}
Update
After received some explanations from some friendly Software Engineer, I understood that the comparator define the order of elements in a Collections. For example, when compare a and b, if the comparator return -1 then a should be put before b in the list.
Key thing to remember is if comparison returns positive value ( >0) swap happens. Otherwise not during sorting algorithm.
Example:
4(a) 2(b) 6
For ascending order:
a > b (4 > 2) return 1 (swap requires between a and b i.e place 2 4 6)
For descending order:
a > b ( 2 > 4 ) return -1 (swap not needed between a and b i.e place 4 2 6, because it is already in order).
This logic is implemented under the sorting algorithm. So, if a and b are already in order as you expected, then return -1; otherwise, return 1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With