Overriding hashcode and equals in java
<p>I am unclear about use of hashcode and equals method in java.I have following query</p>

<p><strong>First</strong>  </p>

<p>If I Override only equals method all objects of value Fred are added though HashSet implements set interface,which cant take repeated values.</p>

<p><strong>Second</strong>
If i override both equals and hashcode only one object is added to HashSet.Why?</p>

<p><strong>Third</strong>
If I implement only equals in this case will removing  one Fred object will remove all?</p>

<pre><code>class Person
{
    String name;
    Person(String name) {
        this.name=name;
    }

    @Override
    public boolean equals(Object obj) {
        if(!(obj instanceof Person))
        {
       return false;
         }
    Person p = (Person)obj;
    return p.name.equals(this.name);
       }


    /*@Override
    public int hashCode() {
        return name.hashCode();
    }*/
}

public class HashSetDemo {

    /*
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        HashSet&lt;Person&gt; s= new HashSet&lt;Person&gt;();
        s.add(new Person("Fred"));
        s.add(new Person("Fred"));
        s.add(new Person("Fred"));
        s.add(new Person("Fred1"));
        for(Person a:s) {
            System.out.println(a.name);
        }

        s.remove(new Person("Fred"));
        System.out.println(s);
    }
}
</code></pre>
