Return type from a Comparator

Viewed 59594

What does the return value inside the Comparator actually mean?

For example :

class TreeSetDemo
{
    public static void main(String arg[])
    {
        TreeSet t=new TreeSet(new MyComparator());
        t.add(new Integer(20));
        t.add(new Integer(10));
        t.add(new Integer(30));
        t.add(new Integer(100));
        System.out.println(t); 
    }    

    class MyComparator implements Comparator 
    {    
        public int compare(Object o1, Object o2) 
        {
            return 0;
        }
    }
}

If the return type is 1 then its actually returning

[20, 10, 30, 100]

If the return type is -1 then its actually returning

[100, 30, 10, 20]

If the return type is 0 then its actually returning

[20]

Please tell me what does this indicate?

7 Answers
PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>(){
           @Override
           public int compare(Integer o1, Integer o2) {
               if(o1.intValue() > o2.intValue()){
                   return -1;
               }else if(o1.intValue() < o2.intValue()){
                   return 1;
               }
               return 0;
           }
       });
       pq.add(44);
       pq.add(3);
       pq.add(2);pq.add(5); 
System.out.println(pq.poll());
//outpu 44

it will sort the element when adding to elements to it in descending order. it will compare two objects based on the return value it will maintain the order.

Related