I'm working on an application that allows the user to manage accounts. So, suppose I have an Account
class, representing one of the user's accounts:
class Account
{
public int id;
public String accountName;
public String accountIdentifier;
public String server;
public String notes;
}
My equals
method looks like this:
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'm only comparing the accountIdentifier
and the server
, but not the other fields. There are several reasons why I chose this approach.
- I keep the accounts in a
List
. When the user updates an account, by changing the account name (which is just a name specified by the user to identify the account) or the notes, I can doaccountList.set(accountList.indexOf(account), account);
to update the account in the list. Ifequals
compared all properties, this approach wouldn't work, and I'd have to work around it (for example by iterating over the list and checking for these properties manually). - This might actually be more important, but it only came to my mind after thinking about it for a while. An
Account
is uniquely identified by theaccountIdentifier
and theserver
it belongs to. The user might decide to rename the account, or change the notes, but it's still the same account. But if the server is changed, I think I would consider it a different account. Theid
is just an internal ID since the accounts are stored in a database. Even if that changed, the account is still considered the same account if theaccountIdentifier
and theserver
stayed the same.
What I'm trying to say is that I basically implemented equals
this way to allow for shorter, more concise code in the rest of the application. But I'm not sure if I'm breaking some rules here, or if I'm doing something that might cause other developers headaches if it ever happens that someone is working with my application's API.
Is it okay to only compare some fields in the equals
method, or should I compare all fields?