[英]HashMap not retrieving both values even after overriding hashcode & equals for same object
[英]Hash Collisions even after overriding equals and hashcode methods for object being stored as key in Hashmap
我需要將類邊緣的對象類型存儲為Key,將ArrayList存儲為Value
public class edge {
String edgeType; // Horizontal or Vertical edge
int i; //i and j for a cell in 2D matrix
int j;
}
HashMap<edge, ArrayList<String>> edgeHM = new HashMap<edge, ArrayList<String>>();
每個鍵的值Arraylist初始化為0和1
當我使用功能reduceEdgeDomain
檢索和編輯條目之一時,多個鍵將使用該值進行更新。 哈希沖突? 例如。 需要更新密鑰H21
,密鑰更新H21
和V21
(edgetype, i, j)
H22 <-> V22 or V53 <-> H53
public static void reduceEdgeDomain(HashMap<edge, ArrayList<String>> edgeHM, ArrayList<edge> nonEssEdges){
ArrayList<String> tempAL;
for(int i=0; i<nonEssEdges.size(); i++)
{
edge str = nonEssEdges.get(i);
if(edgeHM.containsKey(str)){
tempAL = edgeHM.get(str);
edgeHM.remove(str);
tempAL.remove("1");
edgeHM.put(str, tempAL);
}
}
}
覆蓋equals()
和hashcode()
public boolean equals(Object o){
if (this == o){
return true;
}
if(!(o instanceof edge)){
return false;
}
edge edge = (edge) o;
return i==edge.i && j==edge.j && Objects.equals(edgeType, edge.edgeType);
}
@Override
public int hashCode() {
String uniqueIdentified = edgeType + i + j;
MessageDigest digest = null;
try {
digest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
byte[] hash = digest.digest(uniqueIdentified.getBytes(StandardCharsets.UTF_8));
ByteBuffer wrapped = ByteBuffer.wrap(hash); // big-endian by default
short num = wrapped.getShort();
return num;
}
您使用short作為哈希。 短值只有65536個,因此您可能很不幸。 就像@JBNizet指出的那樣,在這里使用SHA-256並不是很有用,這會使您的代碼慢得多。
所以呢? ,哈希沖突是正常的,因為字符串的長度是無限的,因為字符串有無限可能的組合和排列,但是字符串的長度是無限的,但是java中的哈希碼是“ int”,其范圍有限,因此無需擔心。 哈希碼沖突是正常的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.