title: Should I compare all fields in my class's "equals" method?
body: <p>I'm working on an application that allows the user to manage accounts. So, suppose I have an <code>Account</code> class, representing one of the user's accounts:</p>
  
  
  
  <pre class="lang-java prettyprint-override"><code>class Account
  {
      public int id;
      public String accountName;
      public String accountIdentifier;
      public String server;
      public String notes;
  }
  </code></pre>
  
  <p>My <code>equals</code> method looks like this:</p>
  
  <pre class="lang-java prettyprint-override"><code>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;
  }
  </code></pre>
  
  <p>As you can see, I'm only comparing the <code>accountIdentifier</code> and the <code>server</code>, but not the other fields. There are several reasons why I chose this approach.</p>
  
  <ol>
  <li>I keep the accounts in a <code>List</code>. 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 do <code>accountList.set(accountList.indexOf(account), account);</code> to update the account in the list. If <code>equals</code> 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).</li>
  <li>This might actually be more important, but it only came to my mind after thinking about it for a while. An <code>Account</code> is uniquely identified by the <code>accountIdentifier</code> and the <code>server</code> 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. The <code>id</code> 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 the <code>accountIdentifier</code> and the <code>server</code> stayed the same.</li>
  </ol>
  
  <p>What I'm trying to say is that I basically implemented <code>equals</code> 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.</p>
  
  <p><strong>Is it okay to only compare some fields in the <code>equals</code> method, or should I compare all fields?</strong></p>