作者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
推 tkcn:hashCode() 看起來有點怪怪的 @@a 03/05 18:17
→ adrianshum:有幾個 hashCodeCache 改漏了 XD 現在改 03/07 23:33
※ 編輯: adrianshum 來自: 219.77.15.243 (03/07 23:33)