3 回答

TA贡献1811条经验 获得超5个赞
我不确定它有什么意义,但除非我误解了,否则它可以满足您的要求:
public class Date {
private int year;
private int month;
private int day;
// Constructor etc.
@Override
public boolean equals(Object obj) {
Date otherDate = (Date) obj;
return Boolean.logicalAnd(year == otherDate.year,
Boolean.logicalAnd(month == otherDate.month, day == otherDate.day));
}
@Override
public int hashCode() {
return Objects.hash(year, month, day);
}
}
我正在使用Boolean类方法(类中的静态方法Boolean)logicalAnd而不是&&. 由于在调用方法之前对每个参数进行评估,因此不会像这样使评估短路&&。否则,它会给出相同的结果。由于您有三个子条件并且该方法只接受两个参数,因此我需要将一个调用嵌套为第一个调用中的参数之一。
正如评论中所说,该方法需要返回一个原语boolean(small b)并且应该有一个@Override注释。此外,在覆盖时equals,最好也覆盖hashCode并确保相等的对象具有相等的哈希码。
对于生产代码,人们会使用内置的LocalDate而不是编写自己的Date类。LocalDate已经覆盖了equalsand hashCode,我们无需担心它们是如何实现的。

TA贡献1836条经验 获得超13个赞
也许我们可以尝试不同的方法。
第一: 方法 compareDates 通过格式化日期来丢弃时间。
public class EqualityDates {
public static void main(String[] args) throws ParseException {
System.out.println(compareDates(10,0,2019).equals(compareDates(1,0,2019)));
}
private static Date compareDates(int day, int month, int year) throws ParseException {
MyDate myDate = new MyDate();
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, day);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.YEAR, year);
myDate.setMyDate(formatter.parse(formatter.format(cal.getTime())));
return myDate.getMyDate();
}
}
然后: MyDate 类覆盖 Equals 和 HashCode 来比较日期。
class MyDate {
Date myDate;
public Date getMyDate() {
return myDate;
}
public void setMyDate(Date myDate) {
this.myDate = myDate;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
MyDate otherDate = (MyDate) obj;
if (myDate == null) {
if (otherDate.myDate != null) return false;
} else if (!myDate.equals(otherDate.myDate)) return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((myDate == null) ? 0 : myDate.hashCode());
return result;
}
}
这只是一个尝试!

TA贡献1831条经验 获得超10个赞
两个日期对象总是可以使用它们自己的 equals 方法进行比较,该方法以毫秒为单位使用 getTime() 并进行比较。
date1.equals(date2);// returns boolean
你不能覆盖布尔类的equals方法,因为这个类是final的,所以不能扩展。
添加回答
举报