3 回答

TA貢獻1811條經(jīng)驗 獲得超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類方法(類中的靜態(tài)方法Boolean)logicalAnd而不是&&. 由于在調(diào)用方法之前對每個參數(shù)進行評估,因此不會像這樣使評估短路&&。否則,它會給出相同的結(jié)果。由于您有三個子條件并且該方法只接受兩個參數(shù),因此我需要將一個調(diào)用嵌套為第一個調(diào)用中的參數(shù)之一。
正如評論中所說,該方法需要返回一個原語boolean(small b)并且應(yīng)該有一個@Override注釋。此外,在覆蓋時equals,最好也覆蓋hashCode并確保相等的對象具有相等的哈希碼。
對于生產(chǎn)代碼,人們會使用內(nèi)置的LocalDate而不是編寫自己的Date類。LocalDate已經(jīng)覆蓋了equalsand hashCode,我們無需擔(dān)心它們是如何實現(xiàn)的。

TA貢獻1836條經(jīng)驗 獲得超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條經(jīng)驗 獲得超10個贊
兩個日期對象總是可以使用它們自己的 equals 方法進行比較,該方法以毫秒為單位使用 getTime() 并進行比較。
date1.equals(date2);// returns boolean
你不能覆蓋布爾類的equals方法,因為這個類是final的,所以不能擴展。
添加回答
舉報