title: Evaluating objects containing Strings with Java ArrayList contains()
body: <p>I would like to do a deeper String check of Objects to be able to do the following:</p>
  
  <pre><code>List&lt;MyObj&gt; myList = new ArrayList&lt;MyObj&gt;() {{
      add(new MyObj("hello"));
      add(new MyObj("world"));
  }};
  
  System.out.println(myList.contains("hello")); // true
  System.out.println(myList.contains("foo")); // false
  System.out.println(myList.contains("world")); // true
  </code></pre>
  
  <p>But getting false on each one with the following full code</p>
  
  <pre><code>/* Name of the class has to be "Main" only if the class is public. */
  class Ideone {
      public static class MyObj {
          private String str;
          private int hashCode;
  
          public MyObj(String str) {
              this.str = str;
          }
  
          public @Override boolean equals(Object obj) {
              System.out.println("MyObj.equals(Object)");
              if (obj == this) {
                  return true;
              }
  
              if (obj instanceof String) {
                  String strObj = (String) obj;
                  return strObj.equals(str);
              }
  
              return false;
          }
  
          public @Override int hashCode() {
              if (hashCode == 0) {
                  hashCode = 7;
                  for (int i = 0; i &lt; str.length(); ++i) {
                      hashCode = hashCode * 31 + str.charAt(i);
                  }
              }
  
              return hashCode;
          }
      }
  
      public static final MyObj obj1 = new MyObj("hello");
      public static final MyObj obj2 = new MyObj("world");
      public static void main (String[] args) throws java.lang.Exception {
          List&lt;MyObj&gt; myList = new ArrayList&lt;MyObj&gt;() {{
              add(obj1);
              add(obj2);
          }};
  
          System.out.println(myList.contains("hello"));
          System.out.println(myList.contains("foo"));
          System.out.println(myList.contains("world"));
      }
  }
  </code></pre>
  
  <p>If I'm right the List Object should use <code>equals()</code> and <code>hashCode()</code> to evaluate containing Objects.
  So I <code>@Override</code> them and check their Strings additionally.
  But it never gets into <code>equals()</code> as there's no output <code>MyObj.equals(Object)</code>.</p>