/* Use HashSet to store custom elements HashSet Collection guarantees element uniqueness by: Two methods, hashcode and equals. If the hashcode value of the element is the same, the equals is not determined to be true. If an element has a different hashcode value, equals is not called. Both of these methods are called by HashSet and are not explicitly called. Note: For actions that determine whether an element exists, and so on, the method of dependency is the hashcode of the element and the Equals method. */import java.util.*;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;} public int hashcode () {return name.hashcode () +age*37;} public boolean equals (Object obj) {if (!) ( obj instanceof person) return false; Person p= (person) Obj;return this.name.equals (p.name) &&this.age==p.age;} Class HashSetDemo1 {public static void main (string[] args) {HashSet hs=new HashSet (); Hs.add (New Person ("lily_1", 30)); Hs.add (New person ("lily_2")), Hs.add (New person ("Lily_3"), Hs.add (New person ("lily_3")), Hs.add (The new person ( "Lily_4"), Hs.add ("Lily_4"), Hs.add (New person ("Lily_5"), Hs.remove (The New person ("lily_5", 30)) ; Iterator It=hs.iterator (); while (It.hasnext ()) {PeRson p= (person) it.next (), SOP (P.getname () + "..." +p.getage ()); System.out.println ("Hello world!");} public static void Sop (Object obj) {System.out.println (obj);}}
Set: Elements are unordered (the order in which they are deposited and taken out is not necessarily consistent), and elements cannot be duplicated.
The HashSet is based on a hash table.
Features of the hash table:
The hash table is the hash address value of the object, and when the new object address is added, the
First determine if there is no value for this address in the hash table,
If so, then it is the same object, if not, then it is saved.
If not, it is stored.
This feature determines that the HashSet set is unordered and non-repeatable.
Java Collection Framework-hashset