void TestConflicting() { String s1 = "Hello"; String s2 = "World"; int x1 = 17 * 17 + s1.GetHashCode(); int x2 = 17 * 17 + s2.GetHashCode(); HashCodeExample h1 = new HashCodeExample(x2 * 37, s1); HashCodeExample h2 = new HashCodeExample(x1 * 37, s2); Hashtable ht = new Hashtable(); ht.Add(h1, null); ht.Add(h2, null); }
void Test() { String s1 = "Hello"; String s2 = "World"; // calculating hashcode according to HashCodeAutomater // to find the collison Console.WriteLine("s1 (" + s1.GetHashCode() + ")"); Console.WriteLine("s2 (" + s2.GetHashCode() + ")"); int x1 = 17 * 17 + s1.GetHashCode(); int x2 = 17 * 17 + s2.GetHashCode(); HashCodeExample h1 = new HashCodeExample(0, s1); HashCodeExample h2 = new HashCodeExample(x1 * 37 - x2 * 37, s2); Console.WriteLine("HashCode " + h1.GetHashCode() + " Object " + h1); Console.WriteLine("HashCode " + h2.GetHashCode() + " Object " + h2); Console.WriteLine(h1 + (h1.Equals(h2) ? "==" : "!=") + h2); // 2nd collison pair h1 = new HashCodeExample(x2 * 37, s1); h2 = new HashCodeExample(x1 * 37, s2); Console.WriteLine("HashCode " + h1.GetHashCode() + " Object " + h1); Console.WriteLine("HashCode " + h2.GetHashCode() + " Object " + h2); Console.WriteLine(h1 + (h1.Equals(h2) ? "==" : "!=") + h2); try { System.Collections.Hashtable ht = new System.Collections.Hashtable(); ht.Add(h1, null); ht.Add(h2, null); } catch (System.Exception ex) { Console.WriteLine("Ex (" + ex.ToString() + ")"); if (!h1.Equals(h2)) { throw new Exception("Ouch, same hashcode different state", ex); } } //Console.WriteLine("hit the any key key (enter;-)"); //Console.ReadLine(); }