title: Java hashcode: Object vs composite
body: <p>I've stumbled on this method in some code whose only purpose is to create a String <code>Key</code> for a <code>HashMap</code> (EDIT: In my case all of X, Y and Z will be numeric, consider them co-ordinates if that makes it easier):</p>
  
  <pre><code>protected String createMappingKey(String x, String y, String z) {
          return x+":"+y+":"+z;
  }
  </code></pre>
  
  <p>Something about this code is not sitting right and I think it would be better to be replaced with an object like so (note that this code has been generated by my IDE so you can change the implementation however you'd like):</p>
  
  <pre><code>public static class MyKey {
          String x,y,z;
  
          // Constructor(s), maybe getters and setters too here
  
          @Override
          public boolean equals(Object o) {
              if (this == o) return true;
              if (o == null || getClass() != o.getClass()) return false;
  
              MyKey myKey = (MyKey) o;
  
              if (x != null ? !x.equals(myKey.x) : myKey.x != null) return false;
              if (y != null ? !y.equals(myKey.y) : myKey.y != null) return false;
              if (z != null ? !z.equals(myKey.z) : myKey.z != null) return false;
  
              return true;
          }
  
          @Override
          public int hashCode() {
              int result = x != null ? x.hashCode() : 0;
              result = 31 * result + (y != null ? y.hashCode() : 0);
              result = 31 * result + (z != null ? z.hashCode() : 0);
              return result;
          }
      }
  </code></pre>
  
  <p>But this seems like an awful lot of code for not a lot of value.  I'm pretty sure there will only be a negligible difference in the number of collisions between these two approaches.</p>
  
  <p>Which of these approaches would you prefer and why?  Is there a better approach that I'm missing?  </p>
  
  <p>If one of these approaches will have a significant number of collisions more than the other then that would also interest me and I'll open a separate question to deal with that.  </p>