Re: [問題] hashtable的問題

看板java作者 (Alien)時間15年前 (2010/03/05 17:49), 編輯推噓1(101)
留言2則, 2人參與, 最新討論串4/5 (看更多)
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

03/05 18:17, , 1F
hashCode() 看起來有點怪怪的 @@a
03/05 18:17, 1F

03/07 23:33, , 2F
有幾個 hashCodeCache 改漏了 XD 現在改
03/07 23:33, 2F
※ 編輯: adrianshum 來自: 219.77.15.243 (03/07 23:33)
文章代碼(AID): #1BaDEW9r (java)
文章代碼(AID): #1BaDEW9r (java)