HashSet: Storing strings and traversing
Question: Why does the string content store only one when the string is stored?
By looking at the source of the Add method, we know that this method relies on two methods: Hashcode () and Equals ().
Steps:
First, compare the hash value
If same, go ahead, compare address values or go to equals ()
If it is different, add it directly to the collection
Follow the steps of the method:
First see if the hashcode () value is the same
Same: Continue to the Equals () method
Returns true: Indicates that the element is duplicated and does not add
Returns false: The description element is not duplicated and is added to the collection
Different: Add elements directly to the collection
If the class does not override both methods, the object () is used by default. Generally different.
The string class overrides the Hashcode () and Equals () methods, so it can remove the same string of content. Only one left.
1 ImportJava.util.HashSet;2 Public classHashsetdemo {3 Public Static voidMain (string[] args) {4 //To create a collection object5hashset<string> HS =NewHashset<string>();6 7 //Creating and adding elements8Hs.add ("Hello");9Hs.add ("World");TenHs.add ("Java"); OneHs.add ("World"); A - //iterating through the collection - for(String s:hs) { the System.out.println (s); - } - } - } + -
Requirements: Store custom objects and guarantee the uniqueness of the elements
Requirement: If the member variable values for two objects are the same, then the same element.
This is not what I asked for at the moment: because we know that hashset is dependent on the hashcode () and Equals () methods.
These two methods are not rewritten in the student class, so the object class is used by default.
At this time, their hash value will not be the same, and will not continue to judge, to perform the addition operation.
1 ImportJava.util.HashSet;2 Public classHashSetDemo2 {3 Public Static voidMain (string[] args) {4 //To create a collection object5hashset<student> HS =NewHashset<student>();6 7 //Create student Objects8Student S1 =NewStudent ("Brigitte", 27);9Student s2 =NewStudent ("spokesperson", 22);TenStudent s3 =NewStudent ("Condom", 30); OneStudent S4 =NewStudent ("Brigitte", 27); AStudent S5 =NewStudent ("Brigitte", 20); -Student s6 =NewStudent ("Fan Bingbing", 22); - the //adding elements - Hs.add (S1); - hs.add (S2); - Hs.add (S3); + Hs.add (S4); - Hs.add (S5); + Hs.add (S6); A at //iterating through the collection - for(Student s:hs) { -System.out.println (S.getname () + "---" +s.getage ()); - } - } -}
Java 17-3 hashcode () method