Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package test;
- import java.util.HashSet;
- import java.util.Set;
- public class HashMapTest {
- public static void main(String[] args) {
- Set<TestClass> set = new HashSet<>();
- // Insert 10 unequal objects to ensure treeified bin
- for (int i = 0; i < 10; i++)
- set.add(new TestClass(i, 0));
- // The next two objects inserted into the set are equal, and the second should replace the first,
- // totalling 11 objects in the set.
- // Next object is going on the far left of the tree
- set.add(new TestClass(-1, -1));
- // Final object goes on the far right of the tree
- set.add(new TestClass(-1, 1));
- System.out.println(set.size()); // If everything goes well, this should print 11. But due to JDK bug it prints 12.
- }
- /**
- * Class designed to demonstrate the bug. A class with inconsistent equals and compareTo is rare in practice,
- * and when it does occur, it tends to be messier than this to exploit. Also, unless the hash function is bad
- * (as in this case for ease of demonstration), you have to deliberately find pairs of unequal objects whose
- * hashcode collide.
- */
- private static class TestClass implements Comparable<TestClass> {
- private final int accordingToEquals;
- private final int accordingToComparator;
- public TestClass(int accordingToEquals, int accordingToComparator) {
- this.accordingToEquals = accordingToEquals;
- this.accordingToComparator = accordingToComparator;
- }
- @Override
- public int hashCode() {
- // put everything in the same bin, and force comparison to use the comparator rather than the hash
- // this is just for demonstration, but any hashcode which is equal when equals returns true (as per the contract) should work
- return 0;
- }
- @Override
- public boolean equals(Object other) {
- if (other == this) return true;
- if (!(other instanceof TestClass)) return false;
- TestClass that = (TestClass) other;
- return accordingToEquals == that.accordingToEquals;
- }
- @Override
- public int compareTo(TestClass other) {
- return Integer.compare(accordingToComparator, other.accordingToComparator);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement