title: java LinkedHashSet
body: <p>I've been studying for OCJP (former SCJP) and I came across the following example which uses LinkedHashSet:</p>
  
  <pre><code>public class Test{
  
      int size;
  
      public Test(int s){
         this.size = s;
      }
  
      @Override
      public boolean equals(Object obj) {
           return (this.size == ((Test)obj).size);
      }
  
      public static void main(String[] args) {
        LinkedHashSet&lt;Test&gt; s = new LinkedHashSet&lt;Test&gt;();
        s.add(new Test(1));
        s.add(new Test(2));
        s.add(new Test(1));
        System.out.println(s.size());
      }
  }
  </code></pre>
  
  <p>Now, the question is what is displayed if :<br>
  1) implementation stays as is<br>
  2) override of hashCode is inserted in the class Test as follows:    </p>
  
  <pre><code>public int hashCode() {return size/5};
  </code></pre>
  
  <p>Running and compiling the code states that the size of set in the first case is 3, while in the second it is 2.
  Why?</p>
  
  <p>In case 1, although equals method is overriden, it is never invoked. Does that mean that add() method does not check for object equality if hashCode method is not overriden?<br>
  In case 2, hashCode with the given implementation and the give set of Test objects always returns the same number. How is that different from the default hashCode implementation, and why does it cause equals to be invoked?</p>