[英]How to check if 2 Class instances are the same
例如,我有一個水果課。 我創建了2個實例:
Fruit apple = new Fruit("apple");
Fruit orange = new Fruit("orange");
2個實例的值不相同,因此我正在尋找錯誤的答案。 我重寫了.equals()方法,並編寫了以下方法進行測試:
@Override
public boolean equals(Object otherObject){
if(otherObject instanceof Fruit){
return true;
}
return false;
}
if(apple.equals(orange))
System.out.println("true");
else
System.out.println("false");
上面的方法給了我正確的答案。 根據我的理解,這是正確的答案,因為這只是測試它們是否屬於同一類,這是正確的。
但是我無法繞過實例本身的值進行測試。 請指教。 謝謝。
您應該包括Fruit
課程,但這是一種方法
static class Fruit {
private String name;
public Fruit(String name) {
this.name = name;
}
@Override
public boolean equals(Object otherObject) {
// check for reference equality.
if (this == otherObject) {
return true;
}
if (otherObject instanceof Fruit) {
Fruit that = (Fruit) otherObject;
// Check for name equality.
return (name == null && that.name == null)
|| name.equals(that.name);
}
return false;
}
}
public static void main(String[] args) {
Fruit apple = new Fruit("apple");
Fruit apple2 = new Fruit("apple");
Fruit orange = new Fruit("orange");
if (apple.equals(orange))
System.out.println("true");
else
System.out.println("false");
// You can also use the shorter
System.out.println(apple.equals(apple2));
}
產出
false
true
由於Java使用隱式引用,因此您需要在對象等效性和引用等效性之間進行區別。
如果您只是想知道兩個對象是否使同一存儲單元脫接,因此它們實際上是相同的,則不能使用equals運算符:
Object A = new Fruit("A");
Object B = new Fruit("A");
System.out.println(A == B);
這將打印為false,因為A和B不是同一參考單元。
Object A = new Fruit("A");
Object B = A
System.out.println(A == B);
將返回true,因為它們都是同一個參考單元格的“指針”。
如果您想實現語義相等,我建議您使用equals方法和類的字段。
Object A = new Fruit("A");
Object B = new Fruit("A");
System.out.println(A.equals(B));
在這種情況下應返回true。
為此,您可以對可能編寫的每個類使用以下equals方法:(假設您具有字段A的getter和setter且您的類名為myClass)
public boolean equals(Object B){
if(B instanceof MyClass){
MyClass B = (MyClass) B;
boolean flag = this.getA().equals(B.getA());
return flag;
}
return false;
}
您將必須執行boolean flag = this.getA().equals(B.getA());
針對課程的每個領域。 如果對象字段具有相同的值,則將導致相等。
但是oyu必須記住,沒有完美的equals方法。 java中有一個所謂的哈希碼等於合約,這意味着每當A.hashCode()==B.hashCode()
時, A.equals(B)
必須持有。
標志方法的一個好處是您不必關心對象字段的類型,對於不是對象的基本類型(int,float等),Java運行時將進行隱式的強制轉換和強制轉換將它們轉換為Integer或Float對象,並使用equals方法。
@Override
public boolean equals(Object otherObject){
if(!otherObject instanceof Fruit){
return false;
}
return ((Fruit)otherObject).getName().equals(name);
}
假設“ apple”存儲為您的Fruit的名稱(例如,作為成員String m_name)
然后在您的equals方法中:
if( otherObj instanceof Fruit
&& (Fruit)otherObj.name.equals(this.name))
return true;
else
return false;
怎么樣,簡單容易:
public boolean check(Object ObjectOne, Object ObjectTwo) {
return ObjectOne.getClass() == ObjectTwo.getClass();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.