title: For contains should we override both hashcode and equals for hashset in java
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/27581/overriding-equals-and-hashcode-in-java">Overriding equals and hashCode in Java</a>  </p>
  </blockquote>
  
  
  
  <p>For contains should we override both hashcode and equals for hashset in java?</p>
  
  <pre><code>import java.lang.Math;
  import java.util.HashSet;
  class Hello{
  
      public String name= ""; 
  
      Hello(String name){
          this.name = name;   
      }
  
  
      public static void main(String args[]){
  
          Hello h1 = new Hello("first");
          Hello h2 = new Hello("second");
          Hello h3 = new Hello("third");
          Hello h4 = new Hello("fourth");
          Hello h5 = new Hello("fourth");
  
          HashSet hs = new HashSet(); 
          hs.add(h1);
          hs.add(h2);
          hs.add(h3);
          hs.add(h4);
          hs.add(h5);
          hs.add(h5);
          hs.add(null);
  
          System.out.println("elements in hashset"+hs);
          // System.out.println("elements in hashset"+hs.contains());
          System.out.println("elements in hashset"+hs.contains(new Hello("fourth")));
  
      } 
  
      /*public boolean equals(Object obj){
          System.out.println(name+"==========="+((Hello)obj).name);
          if(name.equals(((Hello)obj).name))
              return true;
          else
              return false;
      }*/
  
      public int hashCode(){    
          return name.hashCode();    
      }    
  }
  </code></pre>