一段時間以來第一次在這里發帖,所以如果我犯了任何錯誤,我很抱歉。
我正在從 MOOC fi 學習 Java。我目前在第 5 周,這里提到要比較兩個物件,您必須執行以下操作:
public class SimpleDate {
private int day;
private int month;
private int year;
public SimpleDate(int day, int month, int year) {
this.day = day;
this.month = month;
this.year = year;
}
public boolean equals(Object compared) {
// if the variables are located in the same position, they are equal
if (this == compared) {
return true;
}
// if the type of the compared object is not SimpleDate, the objects are not equal
if (!(compared instanceof SimpleDate)) {
return false;
}
// convert the Object type compared object
// into a SimpleDate type object called comparedSimpleDate
SimpleDate comparedSimpleDate = (SimpleDate) compared;
// if the values of the object variables are the same, the objects are equal
if (this.day == comparedSimpleDate.day &&
this.month == comparedSimpleDate.month &&
this.year == comparedSimpleDate.year) {
return true;
}
// otherwise the objects are not equal
return false;
}
@Override
public String toString() {
return this.day "." this.month "." this.year;
}
}
所以我很困惑,什么是:
public boolean equals(Object compared) {
// if the variables are located in the same position, they are equal
if (this == compared) {
return true;
}
上面的代碼實際上是做什么的?位于同一位置是什么意思?
只檢查物件是否屬于特定型別別,然后比較它們的實體變數以查看它們是否相等不是更好嗎?
uj5u.com熱心網友回復:
this并且compared在您的情況下都是對物件的參考。
在 Java 中,每個物件都駐留在特定的記憶體位置。兩個不同的物件不能同時擁有相同的記憶體位置。
相等運算子或“==”根據兩個物件是否位于相同的記憶體地址來比較它們。因此,只有當它比較的兩個物件參考代表完全相同的物件時,“==”運算子才會回傳真,否則“==”將回傳假。
另請注意,==運算子equals與類上的方法不同。
您可以在以下位置閱讀更多資訊:https : //javarevisited.blogspot.com/2012/12/difference-between-equals-method-and-equality-operator-java.html#ixzz79Ev3iZ5P
uj5u.com熱心網友回復:
== : 比較記憶體地址
.equals() : 比較值(用于物件型別)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/313185.html
標籤:爪哇
