fork download
  1. class Scratch {
  2. public static void main(String[] args) {
  3. final Employee jim = new Employee(2, "jim", 10_000);
  4. final Employee ted = new Employee(2, "ted", 35_000);
  5. final Employee john = new Employee(9, "john", 20_000);
  6.  
  7. System.out.println("jim compare to ted: " + jim.compareTo(ted));
  8. System.out.println("john compare to jim: " + john.compareTo(jim));
  9. System.out.println("john compare to ted: " + john.compareTo(ted));
  10. }
  11. }
  12.  
  13. class Employee implements Comparable<Employee> {
  14. int empId;
  15. String empName;
  16. double salary;
  17.  
  18. public Employee(int empId, String empName, double salary) {
  19. this.empId = empId;
  20. this.empName = empName;
  21. this.salary = salary;
  22. }
  23.  
  24. @Override
  25. public int hashCode() {
  26. return empId;
  27. }
  28.  
  29. @Override
  30. public boolean equals(Object o) {
  31. if(this == o) return true;
  32. if(o == null || this.getClass() != o.getClass()) return false;
  33.  
  34. Employee e = (Employee) o;
  35. return (this.empId == e.empId);
  36. }
  37.  
  38. @Override
  39. public String toString() {
  40. return empId + " " + empName + " " + salary;
  41. }
  42.  
  43. @Override
  44. public int compareTo(Employee e) {
  45. if(empId == e.empId)
  46. return 0;
  47.  
  48. if(this.salary < e.salary) {
  49. return -1;
  50. }
  51. else {
  52. return 1;
  53. }
  54. }
  55. }
Success #stdin #stdout 0.14s 48048KB
stdin
Standard input is empty
stdout
jim compare to ted: 0
john compare to jim: 1
john compare to ted: -1