Return type from a Comparator

前端 未结 6 1419
暖寄归人
暖寄归人 2020-12-09 15:16

What does the return value inside the Comparator actually mean?

For example :

class TreeSetDemo
{
    public static void main(String         


        
6条回答
  •  青春惊慌失措
    2020-12-09 16:04

    The return value (not type, the type is int) tells the caller (the thing sorting the data):

    -1 : o1 < o2
    0 : o1 == o2
    +1 : o1 > o2
    

    If you always return the same value (o, 1, -1) for the comparator, regardless of it's inputs, then you're not using it correctly. You need to base the value returned on the values passed in. The idea is that the data structure (or sorter) calls the comparison function any time it needs to order two elements, to find out what order to put them in.

    Its worth noting that the positive/negative integer values (-1, +1) don't need to be 1, they can be any positive/negative numbers. It's just common practice to return -1/+1.

提交回复
热议问题