BAEL-4716 HashMap optimization (#10479)

This commit is contained in:
mdabrowski-eu
2021-02-14 16:51:51 +01:00
committed by GitHub
parent 65520720aa
commit ba83b760d3
7 changed files with 168 additions and 0 deletions
@@ -0,0 +1,6 @@
package com.baeldung.map.hashing;
class Member {
Integer id;
String name;
}
@@ -0,0 +1,8 @@
package com.baeldung.map.hashing;
public class MemberWithBadHashing extends Member {
@Override
public int hashCode() {
return name.hashCode();
}
}
@@ -0,0 +1,18 @@
package com.baeldung.map.hashing;
import com.google.common.base.Charsets;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
public class MemberWithGuavaHashing extends Member {
@Override
public int hashCode() {
HashFunction hashFunction = Hashing.murmur3_32();
return hashFunction.newHasher()
.putInt(id)
.putString(name, Charsets.UTF_8)
.hash().hashCode();
}
}
@@ -0,0 +1,18 @@
package com.baeldung.map.hashing;
public class MemberWithId extends Member {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MemberWithId that = (MemberWithId) o;
return id.equals(that.id);
}
@Override
public int hashCode() {
return id;
}
}
@@ -0,0 +1,23 @@
package com.baeldung.map.hashing;
import java.util.Objects;
public class MemberWithIdAndName extends Member {
public static final int PRIME = 31;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MemberWithObjects that = (MemberWithObjects) o;
return Objects.equals(id, that.id) &&
Objects.equals(name, that.name);
}
@Override
public int hashCode() {
int result = id.hashCode();
result = PRIME * result + (name == null ? 0 : name.hashCode());
return result;
}
}
@@ -0,0 +1,19 @@
package com.baeldung.map.hashing;
import java.util.Objects;
public class MemberWithObjects extends Member {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MemberWithObjects that = (MemberWithObjects) o;
return Objects.equals(id, that.id) &&
Objects.equals(name, that.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
}