Students are looking at this problem, I first raised two questions, and then everyone with questions to see this article will understand better.
- HashSet Why can't I add duplicate elements when I add elements?
- HashSet do you want to add a null element?
Open source, we see the following code, we see HashSet also has a hashmap as a property, HashSet () is constructed by instantiating this map. If you don't know anything about hashmap, you can read my blog post. Also note that there is a static final object present, this is what to use, we continue to look down.
Private transientHashmap<e,object>map; //Dummy value to associate with a Object in the backing Map Private Static FinalObject PRESENT =NewObject (); /*** Constructs a new, empty set; the backing <tt>HashMap</tt> instance has * default initial Capaci Ty (+) and load factor (0.75). */ PublicHashSet () {map=NewHashmap<>(); }
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 inside, if added successfully, then HashMap return null, and then add the success, the last Post also said, Let's talk about it again as a review. If the element is placed inside the HASHMAP, first judge its hashcode, if hashcode not found, according to the Hashcode calculation index placed in the corresponding bucket, if hashcode the same, Then according to whether the key is equals as a second judgment, put in the corresponding linked list inside.
/*** Adds The specified element to this set if it's not already present. * More formally, adds the specified element <tt>e</tt> to this set if * This set contains no element <t T>e2</tt> such that * <tt> (e==null ? e2==null : e.equals (E2)) </tt>. * If This set already contains the element, the call leaves the set * unchanged and returns <tt>false</tt> . * * @parame element to is added to the this set *@return<tt>true</tt> If this set does not already contain the specified * element*/ Public BooleanAdd (e e) {returnMap.put (e, PRESENT) = =NULL;
Of course the second question is whether the students also think, because HashMap is supported by the key is null, so hashset can also add a key null element. HashMap the place so much, you know it's important?!
Core Java simple Talk about HashSet