Uniqueness in sets
<p>If I take for example a <code>HashSet&lt;E&gt;</code>, and add objects to it, how does it check if the object's already there?</p>

<p>I have the following simple setup:  </p>

<pre><code>private class MyObject {
    String text;

    public MyObject(String text) {
        this.text = text;
    }

    @Override
    public boolean equals(Object o) {
        if (o != null &amp;&amp; o instanceof MyObject) {
            return ((MyObject) o).text.equals(text);
        }

        return false;
    }

}
</code></pre>

<p>In my project I have many objects like this, but all initialized separately. I want to filter the doubles, by adding all to a <code>Set</code>, like this:</p>

<pre><code>MyObject m1 = new MyObject("1");
MyObject m2 = new MyObject("1");
MyObject m3 = new MyObject("2");

System.out.println(m1.equals(m2)); //expected: true, result: true
System.out.println(m1.equals(m3)); //expected: false, result: false

Set&lt;MyObject&gt; myObjects = new HashSet&lt;MyObject&gt;();
myObjects.add(m1);
myObjects.add(m2);
myObjects.add(m3);

System.out.println(myObjects.size()); //expected: 2, result: 3

Set&lt;String&gt; stringList = new HashSet&lt;String&gt;();
stringList.add("1");
stringList.add("1");
stringList.add("2");
System.out.println(stringList.size()); //expected: 2, result: 2
</code></pre>

<p>How can I make it so that my <code>myObjects</code> set does not contain these doubles? So <code>m1</code> and <code>m2</code> are different instances, but have the same content so I only need <code>m1</code>.</p>

<p><strong>Edit</strong><br>
Based on Mathias Schwarz's answer I've implemented the <code>hashCode()</code> function as follows:</p>

<pre><code>@Override
        public int hashCode() {
            return text.hashCode();
        }
</code></pre>

<p>But how would I implement this method if I have a more complex class with multiple fields?</p>
