Package Container;import Java.util.hashset;import java.util.iterator;/* Set elements are unordered (the order of deposit and withdrawal is not necessarily consistent), elements cannot be duplicated |--- HashSet: The underlying data structure is a hash table | How does HashSet guarantee the uniqueness of the elements? | is done by two methods to complete the hashcode and equals | If the hashcode value of the element is the same, it will determine if Equals is true | If the hashcode value is not the same, equals is not called | | Note: For actions that determine whether an element exists, and delete it, the dependent method is the |hashcode and equals method of the Element | (ArrayList determines whether an element exists only depending on the Equals method) |---The function of the Treeset:set collection and Collection is a consistent */class person{private String name;private int age; Person (String Name,int age) {this.name = Name;this.age = age;} Public String GetName () {return name;} public int getage () {return age;} Overriding the Hashcode method public int hashcode () {///return 1; This method can also be effective but calls the Equals method, and the comparison is much more//the method calls the Hashcode method of String, it does not call Equals method, less number of comparisons return Name.hashcode () +age*39; The uniqueness of the hashcode value is guaranteed}public boolean equals (Object obj) {if (!) ( obj instanceof person) return false; Person person = (person) Obj;return this.name.equals (person.name) && this.age = = Person.age;}} public class Hashsetdemotwo{public static void sop (Object obj) {System.out.println (obj);} public static void Main (string[] args) {hashset<person> hs = new hashset<person> () Hs.add (The New Person ("A1", 11 ), Hs.add (New Person ("A2"), Hs.add ("A3"), Hs.add (new person ("A4"), Hs.add (New person ("A5", 15)) ; Hs.add (New Person ("A3", 13)); System.out.println (Hs.contains ("A1", 11)));//determine if A1 exists in the set SOP ("Al:" +hs.contains (New Person ("A1", 11)); /Remove A3 from the collection Hs.remove (New person ("A3", 13));//Traverse collection Iterator<person> it = Hs.iterator (); while (It.hasnext ()) {person person = (person) it.next (), SOP (Person.getname () + "= = =" +person.getage ());}}
Java rewrite Hashcode method and Equals method