-2

From the below code I am not understanding two things:

  1. The CompareTo() and Compare() methods return int, but how does this affect the sorting?

  2. The method returns this.name.compareTo(d.name). What is present in this.name?

Please explain elaborately.

import java.util.*;

class Dog implements Comparator<Dog>, Comparable<Dog>{
   private String name;
   private int age;
   Dog(){
   }

   Dog(String n, int a){
      name = n;
      age = a;
   }

   public String getDogName(){
      return name;
   }

   public int getDogAge(){
      return age;
   }

   // Overriding the compareTo method
   public int compareTo(Dog d){
      return (this.name).compareTo(d.name);
   }

   // Overriding the compare method to sort the age 
   public int compare(Dog d, Dog d1){
      return d.age - d1.age;
   }
}

public class Example{

   public static void main(String args[]){
      // Takes a list o Dog objects
      List<Dog> list = new ArrayList<Dog>();

      list.add(new Dog("Shaggy",3));
      list.add(new Dog("Lacy",2));
      list.add(new Dog("Roger",10));
      list.add(new Dog("Tommy",4));
      list.add(new Dog("Tammy",1));
      Collections.sort(list);// Sorts the array list

      for(Dog a: list)//printing the sorted list of names
         System.out.print(a.getDogName() + ", ");

      // Sorts the array list using comparator
      Collections.sort(list, new Dog());
      System.out.println(" ");
      for(Dog a: list)//printing the sorted list of ages
         System.out.print(a.getDogName() +"  : "+
         a.getDogAge() + ", ");
   }
} 
mastov
  • 2,942
  • 1
  • 16
  • 33
Sri
  • 177
  • 2
  • 2
  • 10
  • 3
    Whatever you're doing, it's nonsensical. `Dog` should _not_ implement `Comparator`; you should have a separate class (probably anonymous) implementing `Comparator`. In the meantime, what do you expect `this.name` to be? It's the name of this dog, being compared to another dog. – Louis Wasserman May 16 '16 at 17:50
  • For `compare`, if the dog's ages are the same, they're equal. Otherwise, if the first dog is older, it'll return a positive number, second dog, negative number. – Compass May 16 '16 at 17:52
  • @louis I dint get u sorry – Sri May 16 '16 at 17:59
  • A dog would implement Animal (Dog is a type of Animal), not a Comparator (Dog is not a type of Comparator) – Compass May 16 '16 at 18:05

2 Answers2

1

As you probably guessed, compare and compareTo are used to compare two objects.

How it works

compare(a, b) compares objects a and b. If the returned value is < 0, then a is lower than b. If it is 0, both objects are equal. If it is superior to 0, a is greater than b.

a.compareTo(b) also compares objects a and b. The return value works the same way as for compare. However, when calling it you have to be careful that a is not null, else it throws a NullPointerException.

When to use it

If your class only need one comparison scheme, then only using compareTo is fine.

However, if you need to sort Dog in several ways, for example at one time you want to sort them by age and another time by name, this is where Comparator becomes handy. You can just create two Comparator<Dog>, one which sorts by age and the other by name. When calling a method like sort, you provide as argument the comparator you want to use in order to get the sorting you want.

Relative to your question

The keyword this refers to the current Dog instance. So, this.name is the name of the current Dog instance.

T. Claverie
  • 11,380
  • 1
  • 17
  • 28
0

CompareTo() is used to define the 'natural order' of the objects and creates an int to determine which object is 'greater' than the other and implements Comparable.

a.compareTo(b)<0    //same as a<b     
a.compareTo(b)>0    //same as a>b
a.compareTo(b)==0   //same as a==b
a.compareTo(b)!=0   //same as a!=b
a.compareTo(b)<=0   //same as a<=b
a.compareTo(b)>=0   //same as a>=b

As for how it will sort differently than compare() is entirely up to how you implement the compareTo().

Heres an example on how assuming phoneNumber has 3 fields: areaCode, prefix, lineNumber:

    public  int compareTo(PhoneNumber pn){  
                //  Compare area codes  
            if  (areaCode< pn.areaCode) {   
                return -1;  
            }   
            if  (areaCode > pn.areaCode){   
                    return 1;   
            }   
            //  Area codes are equal, compare prefixes  
            if  (prefix < pn.prefix){   
                    return -1;  
            }   
            if  (prefix > pn.prefix){   
                    return 1;   
            }   
            //  Area codes and prefixes are equal, compare line numbers 
            if  (lineNumber < pn.lineNumber){   
                    return -1;  
            }   
            if  (lineNumber > pn.lineNumber){   
                    return  1;  
            }   
            return  0;  //  All fields  are equal   
            }   

While compare() takes two objects and compares the values between their fields, and implements Comparator

compare(a,b)<0    //same as a<b     
compare(a,b)>0    //same as a>b
compare(a,b)==0   //same as a==b
compare(a,b)!=0   //same as a!=b
compare(a,b)<=0   //same as a<=b
compare(a,b)>=0   //same as a>=b

this answer has a much more elaborate and articulate explanation on comparator and comparable.

Community
  • 1
  • 1
Alkarin
  • 464
  • 7
  • 20