Java Basic Knowledge Hardening Collection Framework note 39:set Collection HashSet store string and traverse

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.