Spaceship operator (<=>) delegates the call to
compareTo method of the object.
Previous
Next
Home
HelloWorld.groovy
public class Employee implements Comparable<Employee>{ String firstName, lastName; Integer salary; Employee(String firstName, String lastName, int salary){ this.firstName = firstName; this.lastName = lastName; this.salary = salary; } @Override public int compareTo(Employee o) { println "Calling compareTo method" if(o == null) throw new NullPointerException(); return this.salary.compareTo(o.salary); } @Override public String toString(){ return salary +". " + firstName +" " + lastName; } } Employee emp1 = new Employee("krishna", "Gurram", 123456) Employee emp2 = new Employee("KRISHNA", "GURRAM", 23456) Employee emp3 = new Employee("KRISHNA", "GURRAM", 123456) println "emp1 <=> emp2 : ${emp1 <=> emp2}" println "emp1 <=> emp3 : ${emp1 <=> emp3}" println "emp2 <=> emp3 : ${emp2 <=> emp3}"
Output
Calling compareTo method emp1 <=> emp2 : 1 Calling compareTo method emp1 <=> emp3 : 0 Calling compareTo method emp2 <=> emp3 : -1
No comments:
Post a Comment