I've stumbled on this method in some code whose only purpose is to create a String Key for a HashMap (EDIT: In my case all of X, Y and Z will be numeric, consider them co-ordinates if that makes it easier):
protected String createMappingKey(String x, String y, String z) {
return x+":"+y+":"+z;
}
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):
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;
}
}
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.
Which of these approaches would you prefer and why? Is there a better approach that I'm missing?
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.