作者adrianshum (Alien)
看板java
标题Re: [问题] hashtable的问题
时间Fri Mar 5 17:49:17 2010
s 大有给了一个很方便的方法.
我这里也提供一个我自己写, 有时有点用的小 util
public class Pair<F, S> {
private F first;
private S second;
transient private Integer hashCodeCache = null;
public Pair(F first, S second) {
this.first = first;
this.second = second;
}
public F getFirst() {
return first;
}
public S getSecond() {
return second;
}
@Override
public int hashCode() {
if (this.hashCodeCache == null) {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode
+ ((first == null) ? 0 : first.hashCode());
hashCode = prime * hashCode
+ ((second == null) ? 0 : second.hashCode());
this.hashCodeCache = hashCode;
}
return this.hashCodeCache;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Pair<?,?> other = (Pair<?,?>) obj;
if (first == null) {
if (other.first != null) {
return false;
}
} else if (!first.equals(other.first)) {
return false;
}
if (second == null) {
if (other.second != null) {
return false;
}
} else if (!second.equals(other.second)) {
return false;
}
return true;
}
}
因为蛮多情况都要用到 "两个值组合"
用起来就
Map<Pair<String, Integer>, String> map = ....;
map.put(new Pair<String, Integer>("MY_AC_NUM", 1),
"blablabla");
这样.
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 61.238.156.189
1F:推 tkcn:hashCode() 看起来有点怪怪的 @@a 03/05 18:17
2F:→ adrianshum:有几个 hashCodeCache 改漏了 XD 现在改 03/07 23:33
※ 编辑: adrianshum 来自: 219.77.15.243 (03/07 23:33)