Core Java HashSet (recommended)

When the students are looking at this question, I first put forward two questions, and then you will understand this article better with questions.

1. Why can't HashSet add duplicate elements when adding elements?

2. Add null element to HashSet?

Open the source code and we see the following code. We see that HashSet also has a HashMap as an attribute. The construction method of HashSet () is to instantiate the map. If you don't know about HashMap, you can read my blog. Also note that there is a static final object present. What is this for? Let's continue to look at it.

Then we open its add method, which is to put the element E into the HashMap, and then put the static final object present as value. If the addition is successful, the HashMap returns null, and then the addition is successful. As mentioned in the previous blog post, let's talk about it again for review. If the element is placed in the HashMap, first judge its hashcode. If the hashcode is not found, calculate the index according to the hashcode and put it in the corresponding bucket. If the hashcodes are the same, then judge whether the key equals as the second judgment and put it in the corresponding linked list.

Of course, the second question is whether the students also thought of it. Because HashMap supports null key, HashSet can also add elements with null key. HashMap uses so many places. Do you know it's very important?!

The above core Java talk about HashSet (recommended) is all the content shared by Xiaobian. I hope it can give you a reference and support more programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>