Preferred Equals() Method Implementation
<p>This is a question about how to implement the equals method when I need to find instance of the object in a List given a value that one of the instances my have in their member.</p>

<p>I have an object where I've implemented equals:</p>

<pre><code>class User {

    private String id;

    public User(id) {
        this.id = id;
    }

    public boolean equals(Object obj) {
        if (!(obj instanceof User)) {
            return false;
        }
        return ((User)obj).id.equals(this.id);
    }
}
</code></pre>

<p>Now if I want to find something in the List I would do something like this:</p>

<pre><code>public function userExists(String id) {
        List&lt;Users&gt; users = getAllUsers(); 
        return users.contains(new User(id));
}
</code></pre>

<p>But perhaps this might be a better implementation?</p>

<pre><code>class User {

    private String id;

    public boolean equals(Object obj) {
        if (!(obj instanceof User)) {
            return false;
        }
        if (obj instanceof String) {
            return ((String)obj).equals(this.id);
        }
        return ((User)obj).id.equals(this.id);
    }
}
</code></pre>

<p>With this instead:</p>

<pre><code>public function userExists(String id) {
    List&lt;Users&gt; users = getAllUsers(); 
    return users.contains(id);
}
</code></pre>
