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 }}