我在一些代码中发现了这种方法,其唯一目的是为 HashMap
创建一个字符串 Key
(编辑:在我的情况下,X、Y和Z都将是数字,如果将它们视为坐标,则会更容易理解):
protected String createMappingKey(String x, String y, String z) {
return x+":"+y+":"+z;
}
这段代码中有些问题,我认为最好用一个对象来替换它,代码如下(请注意,此代码已由我的IDE生成,因此您可以根据需要更改实现方式):
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;
}
}
但这似乎是很多代码而没有太多的价值。我相信这两种方法之间碰撞数量的差异只会微不足道。
你更喜欢哪种方法?为什么?还有其他更好的方法吗?
如果其中一种方法的碰撞数量比另一种方法显著增加,那么我也很感兴趣,我将开设一个单独的问题来处理此事。