True or False? And why??? Java HashSet Contains

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.