First,set interface
Concept: The set interface inherits from the collection interface, and unlike the list interface, the elements stored by the set interface are not duplicated.
Second,HashSet collection
Concept: is the implementation class for the set interface, supported by a hash table (actually a HashMap collection). The extraction Order of HashSet collection elements is not the same as the order in which they are stored .
The way to store data using a hash table data structure is to ensure that the element uniqueness depends on:hashcode () and the Equals () method .
2.1 Hash Table
What is a hash table? A combination of linked lists and arrays .
The underlying use of the hash table is also the array mechanism , the array also holds the object, and these objects are stored in the array when the location is very special, when the need to put these objects to the array ,
Then, based on the specific data of these objects, the corresponding algorithm is used to calculate the position of the object in the array, and then the object is stored in the array. And such an array is called a hash array , that is, a hash table .
when you store the element, you need to combine the corresponding algorithm according to the unique data of the element. This algorithm is actually the hashcode method in the object class. Because any object is a subclass of the object class, any object has this method. That is, when the object is stored in the hash table, the hashcode method , object's storage location , you need to be aware that two object Hashcode method calculates , which is called a hash conflict, then the The span style= "color: #ff0000" Will call the object's equals method , compare these two objects is not the same object, equals method returns True, then store in the hash table, returns is False , in the hash table.
Summary: Guaranteed HashSet the only element of the collection, in fact, is based on the object's hashcode and the Equals method to determine . If we store a custom object in the collection, then it is guaranteed to be unique, and the hashcode and equals methods must be replicated to establish a comparison of the current object.
The Hashcode method is used to calculate the hash value.
Hashcode method calculation diagram:
a combination of hash table array and linked list diagram :
2.2HashSet storage of type elements in Javaapi
When you store a type element that is provided in Javaapi in HashSet, you do not need to override the element's hashcode and equals methods , because these two methods, The Javaapi has been rewritten in each class, such as the String class, the integer class, and so on.
Practice Examples:
1. Add elements to the Hashtable and print
ImportJava.util.HashSet;ImportJava.util.Iterator;ImportJava.util.LinkedHashSet; Public classDemo01 {//Hash Table Public Static voidMain (string[] args) {//TODO auto-generated Method Stubmethod1 ();
Method2 ();
Method3 ();
METHOD4 ();
} Public Static voidmethod1 () {HashSet<String> set=NewHashset<string> (); Set.add ("ABC"); Set.add ("ABC"); Set.add ("Ghi"); SYSTEM.OUT.PRINTLN (set); // }
Print Result: Only one "abc" is stored because of uniqueness.
2. Print hash values
// Hashcode method (provided in the object class) Public Static void method2 () { string S1=new String ("abc"); string S2=new string ("abc"); // The hashcode running out of the hash value is the SYSTEM.OUT.PRINTLN (S1.hashcode ()) of the String class ; System.out.println (S2.hashcode ()); }
Print Result: Hash value hashcode ()
3. Add the elements of the custom class to the hash table and print
Custom Person class:
Public classPerson {PrivateString name; Private intAge ; PublicPerson () {}//overloaded construction methods, assigning values at creation time PublicPerson (String name,intAge ) { Super(); This. Name =name; This. Age =Age ; } @Override//Convert to String PublicString toString () {return"Person [name=" + name + ", age=" + Age + "]"; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } Public intGetage () {returnAge ; } Public voidSetage (intAge ) { This. Age =Age ; } @Override//overriding the Hashcode () method Public inthashcode () {returnName.hashcode () +age*31; } @Override//overriding the Equals () method Public Booleanequals (Object obj) {if( This==obj) { return true; } if(obj==NULL){ return false; } if(objinstanceofPerson ) {Person P=(person) obj; returnName.equals (p.name) &&age==P.age; } return false; }}
Test class Method:
Public Static void method3 () { HashSet<Person> set=new hashset<person>(); Set.add (new person ("a", +)); Set.add (new person ("a", ten)); Set.add (new person ("B", +)); Set.add (new person ("B", +)); SYSTEM.OUT.PRINTLN (set); }
Run Result: Duplicate elements are not stored in the collection because the Hashcode method is overridden with the Equals method
Three, Linkedhashset collection:
We know that HashSet guarantees the element is unique, but the elements are stored in no order, then we must ensure orderly , how to do?
Under HashSet there is a subclass Linkedhashset, which is a data storage structure for the combination of linked lists and hash tables.
Example: An iterator iterates through an ordered unique output:
//iterators Traverse ordered unique outputs Public Static voidmethod4 () {Linkedhashset<String> set=NewLinkedhashset <String>(); Set.add (A); Set.add ("AABBB"); Set.add ("Zhang San"); Set.add ("John Doe"); Set.add (A); Set.add ("John Doe"); Iterator it=Set.iterator (); while(It.hasnext ()) {System.out.println (It.next ()); }
Running results: printing in order of storage
Iv. the principle of judging the unique elements of a set
The contains method of 4.1ArrayList to determine the principle of repetition of elements
The contains method of ArrayList uses the calling method when the Equals method of the passed-in element is compared to the old element in the collection , which is judged by the returned Boolean value whether there are duplicate elements .
(True has, false is None ). At this point, when ArrayList stores a custom type , the custom type determines whether the duplicate is based on the address value before the Equals method is overridden.
So if you want to determine whether a repeating element is based on content, you need to override the Equals method of the element .
4.2HashSet of Add/contains and other methods to determine whether the element repeats the principle
The set collection cannot hold duplicate elements, and the Add method will determine whether there are duplicate elements when added, which are not added or duplicated.
HashSet The collection is unordered, its judgment is only based on the hashcode of the element type and the return result of the Equals method . The rules are as follows:
determine the hashcode value of the new element and the old element already in the collection
if different , the description is a different element that is added to the collection.
L If the same , then judge equals comparison results. Returns true for the same element, or false to add a different element to the collection.
Therefore, using HashSet to store custom types , if you do not override the class's hashcode with the Equals method, then when judging duplicates, you are using the address value, if you want to compare elements by content is the same,
you need to override the hashcode of the element class with the Equals method .
Java Learning (set interface, HashSet collection)