簡體   English   中英

如何比較對象的私有數據字段以確保它們是相同的(Java)?

[英]How to compare private data fields of objects to ensure they are the same (Java)?

剛開始,這是家庭作業/實驗室,我正在尋求建議。 我正在開發一個非常小的程序,它本質上是一個具有最小/最大值約束的計數器和一個將值推高的方法,另一個將值推回零的方法。因此,我的Counter類的私有數據字段是:

private int minimum; 
private int maximum; 
private int currentValue; 

我遇到的麻煩是使用一種方法將我的Counter Class與基於同一類的另一個理論對象進行比較。 在這種情況下,我們希望看到兩個對象之間的數據字段是相同的。 我已經研究了幾種方法,包括使用反射和着名的EqualsBuilder,但是在實現每個方面都遇到了麻煩。

這是他們給我的代碼。

public boolean equals(Object otherObject)
{
    boolean result = true;
    if (otherObject instanceof Counter)
    {

    }
    return result;
}

假設您的equals方法在Counter類中,它可以訪問該類的所有私有成員,即使它們是該類的不同實例的成員。

public boolean equals(Object otherObject)
{
    if (otherObject instanceof Counter)
    {
        Counter ocounter = (Counter) otherObject;
        if (this.minimum != ocounter.minimum)
            return false;
        ...
    } else {
        return false;
    }
    return true;
}

實現equals -method可能是一個真正的痛苦,特別是如果你的班級有很多屬性。

用於equals方法的JavaDoc狀態

請注意,通常需要在重寫此方法時覆蓋hashCode方法,以便維護hashCode方法的常規協定,該方法聲明相等的對象必須具有相等的哈希代碼。

並且,如果您檢查JavaDoc的hashCode方法

  • 如果兩個對象根據equals(Object)方法equals(Object) ,則對兩個對象中的每一個調用hashCode方法必須生成相同的整數結果。
  • 如果兩個對象根據equals(Object)方法不相等則不是必需的,則對兩個對象中的每一個調用hashCode方法必須產生不同的整數結果。 但是,程序員應該知道為不等對象生成不同的整數結果可能會提高哈希表的性能。

因此,通常建議您實現兩種方法( equalshashCode )。 下面顯示了一種基於Java 7附帶的java.util.Objects -class的方法.Aarthic.equals(Object,Object)方法處理空檢查,使代碼更簡單,更易於閱讀。 此外, hash-method是創建可與hashCode一起使用的值的便捷方式。

所以,回答你的問題。 要訪問其他對象的屬性,只需執行類型轉換。 之后,您可以訪問其他對象的私有屬性。 但是,請記住在使用instanceof檢查類型后始終執行此操作。

@Override
public boolean equals(Object other) {
    if (other instanceof Counter) { // Always check the type to be safe
        // Cast to a Counter-object
        final Counter c = (Counter) other;

        // Now, you can access the private properties of the other object
        return Objects.equals(minimum, c.minimum) &&
               Objects.equals(maximum, c.maximum) &&
               Objects.equals(currentValue, c.currentValue);
    }
    return false; // If it is not the same type, always return false
}

@Override
public int hashCode() {
    return Objects.hash(currentValue, maximum, minimum);
}

隨着equals為的方法Counter ,您可以訪問所有的私有字段Counter ,所以你可以做這樣的事情:

if (otherObject instanceof Counter)
{
    if (this.minimum != ((Counter) otherObject).minimum) {
        result = false;
    }
    // [...]
}

假設您的類名為Counter並且您為所有私有字段創建了getters (您應該這樣做):

    @Override 
    public boolean equals(Object other) {
        boolean result = false;
        if (other instanceof Counter) {
            Counter c= (Counter) other;
            result = (this.getMinimum() == that.getMinimum() &&
                     this.getMaximum() == that.getMaximum() &&
                     this.getCurrentValue() == that.getCurrentValue());
        }
        return result;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM