Should I compare all fields in the "equals" method of my class?

I am working on an application that allows the user to manage accounts. So, suppose I have a class Accountrepresenting one of the accounts:

class Account
{
    public int id;
    public String accountName;
    public String accountIdentifier;
    public String server;
    public String notes;
}

My method is equalsas follows:

public boolean equals(Object o)
{
    if (this == o)
        return true;
    if (o == null || !(o instanceof Account))
        return false;

    Account other = (Account) o;
    if (!accountIdentifier.equals(other.accountIdentifier))
        return false;
    if (!server.equals(other.server))
        return false;
    return true;
}

As you can see, I compare only accountIdentifierand server, but not other fields. There are several reasons why I chose this approach.

  • List. , ( , ) , accountList.set(accountList.indexOf(account), account);, . equals , , (, ).
  • , , . Account accountIdentifier server, . , - . , , . id - , . , - , accountIdentifier server .

, , , equals , . , , , , - , - API- .

equals ?

+4
5

, . , , , β€” , , . , , (, ) - , .

, , (, ), - , - ; .

, boolean allFieldsEqual(Account other) "" , , ( ).

, , hashCode equals, .

+6

, . accountIdentifier server , , , . - , .

+2

: " ".

, , () . .

, .

+1

-, . ... , , . , .

( ) , , , ORM, 1: M M: N. , , .

:

  • equals, hashCode, , , ..
  • Apache API, equals hashCode. EqualsBuilder HashCodeBuilder. , , .
+1

- , , . accountIdentifier server, , .

You do not want to use more fields than you need, as this will create false positives in your code. This approach is perfect for your needs.

0
source

All Articles