-3
   public int compare(Map.Entry<Integer,Integer> o1, Map.Entry<Integer,Integer> o2){
                if(o1.getValue() < o2.getValue() ){
                    return -1;
                }
                else if(o1.getValue() > o2.getValue()){
                    return 1;
                }
                else{ 
                        if(o1.getKey() < o2.getKey()){
                            return -1;
                        }else{
                            return 1;
                        }
                }
}


public int compare(Map.Entry<Integer,Integer> o1, Map.Entry<Integer,Integer> o2){

                if(o1.getValue() == o2.getValue()){
                    return (o1.getKey() - o2.getKey()); 
                }
                else{
                    return (o2.getValue() - o1.getValue());
                }

} 

As per my understanding above two compare method should give same result but they are behaving differently.

Can somebody help to understand why are they different?

1 Answers1

4

The first one doesn't correctly handle the case where both keys and values are equal.

The second one doesn't correctly handle overflow.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413