I am reading about interfaces in Java. It is mentioned that we have to implement compareTo method for calling “sort” on ArrayList Container, for example Employee class should implement Comparable Interface.
Later it is explained why can’t the Employee class simply provide “compareTo” method without implementing Comparable interface? The reason for interfaces is that Java programming is strongly typed. When making a method call, the compiler needs to be able to check that the method actually exist.
So I am expecting compile time error when I don’t implement “Comparable interface and using Arrays.sort method, but I am not observing compile error, instead getting runtime error. Kindly explain why compile time error is not shown in above scenario
Below is code snippet
package com.vrk.inheritance;
import java.time.*;
import java.util.Arrays;
public class Employee
{
private String name;
private double salary;
private LocalDate hireDay;
public Employee(String name, double salary, int year, int month, int day)
{
this.name = name;
this.salary = salary;
hireDay = LocalDate.of(year, month, day);
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public LocalDate getHireDay()
{
return hireDay;
}
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}
/*public int compareTo(Object otherObject) {
System.out.println("Employee compareTo called");
return 0;
}*/
/**
* equalTo function in employee. Created on 8th Sep 2024
* @param another object to compare to this object
*/
public boolean equals(Object otherObject) {
// quick test to check if objects are identical
if ( this == otherObject) return true;
// must return false if the explicit parameter is null
if(otherObject == null) return false;
// if the classes don't match, they can't be equal
if (getClass() != otherObject.getClass()) return false;
// now we know otherObject is a non-null Employee
var other = (Employee) otherObject;
// test whether the fields have identical value
// Not sure in my setup below line is not working, but online compiler it is working.
// java.util.Objects.equals(this.hireDay, other.hireDay);
return true;
}
public static void main(String[] args) {
var staff = new Employee[3];
// fill the staff array with Manager and Employee objects
staff[0] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
staff[1] = new Employee("Tommy Tester", 40000, 1990, 3, 15);
staff[1] = new Employee("Ravi Tester", 60000, 1999, 4, 16);
Arrays.sort(staff);
}
}
3
If you look at the documentation for Arrays.sort
, you’ll see it doesn’t use generics at all; it just takes an Object[]
. That’s why you don’t get a compilation error.
This is for historical reasons: the method was written before Java introduced generics.
2