Advertisement
Earthcomputer

HashMapTest.java

Oct 18th, 2018
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.37 KB | None | 0 0
  1. package test;
  2.  
  3. import java.util.HashSet;
  4. import java.util.Set;
  5.  
  6. public class HashMapTest {
  7.  
  8.     public static void main(String[] args) {
  9.  
  10.         Set<TestClass> set = new HashSet<>();
  11.  
  12.         // Insert 10 unequal objects to ensure treeified bin
  13.         for (int i = 0; i < 10; i++)
  14.             set.add(new TestClass(i, 0));
  15.  
  16.         // The next two objects inserted into the set are equal, and the second should replace the first,
  17.         // totalling 11 objects in the set.
  18.  
  19.         // Next object is going on the far left of the tree
  20.         set.add(new TestClass(-1, -1));
  21.         // Final object goes on the far right of the tree
  22.         set.add(new TestClass(-1, 1));
  23.  
  24.         System.out.println(set.size()); // If everything goes well, this should print 11. But due to JDK bug it prints 12.
  25.  
  26.     }
  27.  
  28.     /**
  29.      * Class designed to demonstrate the bug. A class with inconsistent equals and compareTo is rare in practice,
  30.      * and when it does occur, it tends to be messier than this to exploit. Also, unless the hash function is bad
  31.      * (as in this case for ease of demonstration), you have to deliberately find pairs of unequal objects whose
  32.      * hashcode collide.
  33.      */
  34.     private static class TestClass implements Comparable<TestClass> {
  35.         private final int accordingToEquals;
  36.         private final int accordingToComparator;
  37.  
  38.         public TestClass(int accordingToEquals, int accordingToComparator) {
  39.             this.accordingToEquals = accordingToEquals;
  40.             this.accordingToComparator = accordingToComparator;
  41.         }
  42.  
  43.         @Override
  44.         public int hashCode() {
  45.             // put everything in the same bin, and force comparison to use the comparator rather than the hash
  46.             // this is just for demonstration, but any hashcode which is equal when equals returns true (as per the contract) should work
  47.             return 0;
  48.         }
  49.  
  50.         @Override
  51.         public boolean equals(Object other) {
  52.             if (other == this) return true;
  53.             if (!(other instanceof TestClass)) return false;
  54.             TestClass that = (TestClass) other;
  55.             return accordingToEquals == that.accordingToEquals;
  56.         }
  57.  
  58.         @Override
  59.         public int compareTo(TestClass other) {
  60.             return Integer.compare(accordingToComparator, other.accordingToComparator);
  61.         }
  62.     }
  63.  
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement