Home > front end >  How to use compareTo() to compare two objects?
How to use compareTo() to compare two objects?

Time:11-18

I'm new to java, and I'm trying to compare two objects of class K. I don't know how to define that a K 3 is smaller than K 7 as both are not integers but K type. Could you show how to compare cat and dog, so that cat < dog. Thus, cat.compareTo(dog) == -1.

Here are my two objects:

K cat = new K(3);

K dog = new K(7);

I extended Comparable in my class in order to compare. I want to compare them, so this is what I did:


public class K extends Comparable<K>{

//CONSTRUCTOR

//METHOD

if (cat.compareTo(dog) == 0){

   System.out.println("Hi");

}else if ((cat.compareTo(dog) == -1){

   System.out.println("Bye");

}else if ((cat.compareTo(dog) == 1){

   System.out.println("Sleep");
}
}

CodePudding user response:

Your class needs to implement Comparable interface, and inside your class you need to override compareTo method (which is in Comparable interface). In this method you will define how your object will be compared to another, on what 'criteria' the comparison will be done.

It's a good practice to implement compareTo method such that, when its return value is 0, it's like two objects are equals (e.g. firstK.compareTo(secondK) == firstK.equals(secondK)).

You can also read Java documentation compareTo documentation.

public class K implements Comparable<K> {
     //Attributes, constructor etc
     @Override
     public int compareTo(final K otherK) {
          /*
          Do what you want to compare them, for example, if your
          K class has a integer field 'value', and you want to compare 
          K's instances based on 'value' field, you can do as follow:
          */
          return Integer.compare(this.value, otherK.getValue());
     }
}

CodePudding user response:

In your class you have to override the compareTo method of the Comparable interface. By the way use implements instead of extends since Comparable is not a class but an interface.

  • Related