1. Overview of the HashSet class:
(1) No guarantee of Set iteration order
(2) In particular, it does not guarantee that the order is constant
2. How HashSet guarantees element uniqueness
(1) The underlying data structure is a hash table (an array of elements when the list is linked)
(2) Hash table relies on the storage of hashes
(3) Adding a function bottom-up relies on two methods:
• int hashcode ()
• boolean equals (Object obj)
3. HashSet stores strings and iterates through:
(1) The code example is as follows:
1 Packagecn.itcast_02;2 3 ImportJava.util.HashSet;4 5 /*6 * HashSet: Store string and Traverse7 */8 Public classHashsetdemo {9 Public Static voidMain (string[] args) {Ten //To create a collection object Onehashset<string> HS =NewHashset<string>(); A - //Creating and adding elements -Hs.add ("Hello"); theHs.add ("World"); -Hs.add ("Java"); -Hs.add ("World"); - + //iterating through the collection - for(String s:hs) { + System.out.println (s); A } at } -}
The results are as follows:
(2) Question: Why are strings stored with the same contents of a string when the strings are stored only one?
Java Basic Knowledge Hardening Collection Framework note 39:set Collection HashSet store string and traverse