Skip to content

Instantly share code, notes, and snippets.

@ZacBlanco
Last active January 23, 2019 19:06
Show Gist options
  • Save ZacBlanco/fc5b108bb9558276e7eda3c236e15d03 to your computer and use it in GitHub Desktop.
Save ZacBlanco/fc5b108bb9558276e7eda3c236e15d03 to your computer and use it in GitHub Desktop.
Java hashCode Tester
package alluxio;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HashCodeTester {
HashMap<Integer, List<Object>> mGroups = new HashMap<>();
private int mCtr = 0;
/**
* Creates a new group of items which should all have equal hash codes but different hash codes
* from other groups
*
* @param items variable number of objects which should hash to the same value
* @return this
*/
HashCodeTester addHashGroup(Object ...items) {
mGroups.put(mCtr, Arrays.asList(items));
mCtr++;
return this;
}
/**
* Tests for equality of hash codes in each group, makes sure there aren't any collisions with
* items in other groups.
*/
void testHash() {
for (Map.Entry<Integer, List<Object>> group: mGroups.entrySet()) {
int itemNum = 0;
int hashCode = 0;
boolean init = false;
for (Object item : group.getValue()) {
if (!init) {
hashCode = item.hashCode();
init = true;
itemNum++;
continue;
}
assertEquals(String.format("[group, item] hashCode [%d %d] does not match [%d, %d]",
group.getKey(), itemNum, group.getKey(), itemNum), item.hashCode(), hashCode);
for (Map.Entry<Integer, List<Object>> otherGroup : mGroups.entrySet()) {
if (group.getKey().equals(otherGroup.getKey())) {
continue;
}
int itemCheckNum = 0;
for (Object checkItem : otherGroup.getValue()) {
assertNotEquals(String
.format("[group, item] hashCode [%d, %d] matches the hash in [%d, %d]",
group.getKey(), itemNum, otherGroup.getKey(), itemCheckNum),
item.hashCode(), checkItem.hashCode());
itemCheckNum++;
}
}
itemNum++;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment