Return type from a Comparator

前端 未结 6 1370
暖寄归人
暖寄归人 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 15:46

    the way comparator is leveraged here is wrong but for clarifying your doubt why only [20] id being written when return value is 0...

    You are using a TreeSet which doesn't hold identical values(Property of Set). So when the values are compared and return value is zero, Java treats them as equal and retain only the first value. Hence, you are seeing only one value in return.

    0 讨论(0)
  • 2020-12-09 15:56

    Comparator documentation -- Returns: a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

    0 讨论(0)
  • 2020-12-09 15:58

    It's about sort algorithm which needs compare.

    Correct:

    class MyComparator implements Comparator<Integer> {
        public int compare(Integer o1, Integer o2) {
            // Calling the Integer class's compareTo method
            return o1.compareTo(o2);
        }
    }
    
    0 讨论(0)
  • 2020-12-09 16:01

    You are confusing return-type and return-value. The return-type is int. The return value is described in the documentation:

    Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-09 16:04

    Depending on how you want to sort based on this comparator you need to place some logic in the comparator. Your comparator only returns 0 which means equal

    class MyComparator implements Comparator {
    
        public int compare(Object o1, Object o2) {
            // TODO Auto-generated method stub
            return o1.compareTo(o2);
        }
    }
    
    0 讨论(0)
提交回复
热议问题