Java hashset Application

Source: Internet
Author: User

When using hashset, Note: 1. If your class has attributes, you should rewrite the equals and hashcode methods. 2. principles to be followed when writing methods, when two classes of equals return true, the hashcode must be equal (consider the hash table conflicts to understand); 3. Do not modify the value in the hashset at will during use, negative results may be inaccurate.

Import Java. util. *; Class r {public int count; Public R (INT count) {This. count = count;} Public String tostring () {return "R (count" + Count + ")";} public Boolean equals (Object OBJ) {If (OBJ instanceof R) {r = (r) OBJ; If (R. count = This. count) return true;} return false;} public int hashcode () {return this. count ;}} public class testhashset {public static void main (string [] ARGs) {hashset HS = new hashset (); HS. add (New R (5); HS. add (New R (-3); HS. add (New R (9); HS. add (New R (-2); system. out. println (HS); iterator it = HS. iterator (); R first = (r) it. next (); first. count =-3; // directly changed. It is best to delete the file before inserting it into the system. out. println (HS); HS. remove (New R (-3); // only the original-3system is found. out. println (HS); system. out. println ("has-3" + HS. contains (New R (-3); // falsesystem. out. println ("has-5" + HS. contains (New R (-5); // false }}

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.