Import Java.util.HashSet; public class MyClass {public String s; Public MyClass (String s) {this.s = s; } public int hashcode () {return s.hashcode (); } public boolean equals (Object obj) {if (obj = = null) return false; if (! ( obj instanceof MyClass)) return false; MyClass other = (MyClass) obj; if (s = = null) {return false; } return (S.equals (OTHER.S)); } public static void Main (string[] args) {hashset<myclass> set = new hashset<myclass> (); MyClass MC1 = new MyClass ("a"); Set.add (MC1); MC1.S = "B"; MyClass MC2 = new MyClass ("B"); if (Set.contains (MC2)) {System.out.println ("True"); } else {System.out.println ("FAlse "); } } }
The result is false
I guess the reason:
When it is stored to the set. The location is worth the hash before using it.
The mc1.s then changed to make the hash value change.
When you call the Contains method, the location that the hash value points to is found. This is although MC1 and MC2 have the same hash value, and true = = Mc1.equeals (MC2). But there is no storage at all at this location, so it returns false .
and then there's a message in the API document that just found set.
Note:great Care must is exercised if mutable objects is used as set elements. The behavior of a set is not specified if the value of an object was changed in a manner that affects equals comparisons wh Ile the object is a element in the set.
This result is false, perhaps due to the implementation of HashSet (hashed hash storage) ~ ~
True or False? And why??? Java HashSet Contains