title: How to implement "equals" method for generics using "instanceof"?
body: <p>I have a class that accepts a <em>generic type</em>, and I want to override the <code>equals</code> method in a non-awkward way (i.e. something that looks clean and has minimal amount of code, but for a very general use case).</p>
  
  <p>Right now I have something like this:</p>
  
  <pre><code>public class SingularNode&lt;T&gt; {
      private T value;
  
      @SuppressWarnings("unchecked")
      @Override
      public boolean equals(Object other){
          if(other instanceof SingularNode&lt;?&gt;){
              if(((SingularNode&lt;T&gt;)other).value.equals(value)){
                  return true;
              }
          }
          return false;
      }
  }
  </code></pre>
  
  <p>Which, I'm guessing, is pretty flawed - I'm doing a cast to <code>SingularNode&lt;T&gt;</code> on the <code>other</code> object, which could potentially <em>throw an error</em>. </p>
  
  <p>Another thing is - when I do <code>if(other instanceof SingularNode&lt;?&gt;)</code> I'm actually not checking exactly the right thing. I actually want to check against type <code>T</code> and not type <code>?</code>. Whenever I try to make the <code>?</code> into <code>T</code>, I get some error like:</p>
  
  <blockquote>
    <p><strong>Cannot perform instanceof check against parameterized type <code>SingularNode&lt;T&gt;</code>. Use the form <code>SingularNode&lt;?&gt;</code> instead, since further generic type information will be erased at runtime</strong></p>
  </blockquote>
  
  <p>How can I get around this? Is there some way to do <code>T.class.isInstance(other);</code> ?</p>
  
  <p>I suppose there's one really ugly hack solution like this:</p>
  
  <pre><code>@SuppressWarnings("unchecked")
  public boolean isEqualTo(Class&lt;?&gt; c, Object obj){
      if(c.isInstance(obj) &amp;&amp; c.isInstance(this)){
          if(((SingularNode&lt;T&gt;)obj).value.equals(value)){
              return true;
          }
      }
      return false;
  }
  </code></pre>
  
  <p>But that just looks really awkward with the extra method parameter, and it's also not a built-in function like <code>equals</code> is.</p>
  
  <p>Any one who understand generics please explain this? I'm not that proficient with Java, as you can clearly see, so please explain with a tad bit more detail!</p>