/*hashset Basic Operation
*--set: Elements are unordered, the order of deposit and withdrawal is inconsistent, the elements cannot be duplicated
* (use hash to determine if the same object)
*----HashSet: The underlying data structure is a hash table,
* The method of ensuring data uniqueness is to invoke the Hashcode () method that is deposited into the element
* and Equals (Object obj) method
* The Equals method is called only if the hashcode value is the same
*
* */
1 ImportJava.util.HashSet;2 ImportJava.util.Iterator;3 Public classStudentcode {4 5 Public Static voidMain (String []args) {6 //define HashSet, and add data7HashSet hs=NewHashSet ();8Hs.add (NewPerson ("Lisi", 11));9Hs.add (NewPerson ("Zhangsan", 22));TenHs.add (NewPerson ("Lisi", 22)); OneHs.add (NewPerson ("Lisi", 11)); A //traversing data (when outputting data with iterators, data operations can only be performed with iterators: Adding and removing changes, not working with objects) - for(Iterator it=hs.iterator (); It.hasnext ();) { -Person p=(person) it.next (); theSystem.out.println ("Name:" +p.getname () + ", Age:" +p.getage ()); - } - } - } + classperson{ - PrivateString name; + Private intAge ; APerson (String name,intAge ) { at This. name=name; - This. age=Age ; - } - PublicString GetName () { - return This. Name; - } in Public intGetage () { - return This. Age; to } + //override the Hashcode () method to return a fixed hash value - Public inthashcode () { the return60; * } $ //override the Equals (Object obj) method to define the required comparison of variablesPanax Notoginseng Public Booleanequals (Object obj) { - //determine if the incoming obj is a variable that is transformed by a person the if(! (objinstanceofPerson )) + return false; A //transforms a person object onto an incoming object thePerson p=(person) obj; + //determine whether two objects are of equal name and age, and equal are considered to be the same object - return This. Name.equals (P.getname ()) && This. age==p.getage (); $ } $}
Java Collection Framework (HashSet custom elements are the same, overriding hashcode and the Equals method)