我正在阅读有关 Java 接口的内容。提到我们必须实现compareTo方法来调用ArrayList容器上的“排序”,例如Employee类应该实现Comparable接口。
稍后解释了为什么Employee类不能简单地提供“compareTo”方法而不实现Comparable接口? 接口的原因是 Java 编程是强类型的。当进行方法调用时,编译器需要能够检查该方法是否确实存在。
因此,当我不实现“Comparable 接口并使用 Arrays.sort 方法时,我预计会出现编译时错误,但我没有观察到编译错误,而是出现运行时错误。请解释为什么上面的场景中没有显示编译时错误
下面是代码片段
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);
}
}