Set and Map in java

Source: Internet
Author: User
Tags comparable

Yesterday, I saw a discussion about the set: the elements in the Set cannot be repeated. How can we tell whether the elements are repeated? Is = or equals () used ()? What are their differences? Many people give the answer: the elements in the Set cannot be repeated, so the iterator () method is used to identify whether or not to be repeated. Equals () is used to determine whether two sets are equal.

I don't understand this answer! First of all, I think Set is just an interface. There should be differences in how different implementations (such as HashSet and TreeSet) are judged! Second, the iterator () method of Set is just to get an iterator and traverse the elements in the set. During traversal, the object is not compared repeatedly! It depends on the method used to identify whether the Set is repeated. It depends on the implementation of the add () method, because once it can be added, it indicates no repetition.

I have read the source code of HashSet and TreeSet:

First, the underlying data structure of HastSet is a Hash table. The advantage of a Hash table is that the query speed is fast (except in the worst case ). For details about the Hash table implementation, google.

Question: How does Hashset determine whether elements are repeated? We know that Hashset is actually a HashMap. The HashSet. add (E e) method only calls map. put (e, Obj). Code:


[Java]
Public boolean add (E e ){
Return map. put (e, PRESENT) = null;
}
Here, PRESENT is a constant and the simplest object. Such a value is hidden in all Set sets! Continue to jump into the put () method of HashMap:

[Java]
Public V put (K key, V value ){
If (key = null)
Return putForNullKey (value );
Int hash = hash (key. hashCode ());
Int I = indexFor (hash, table. length );
For (Entry <K, V> e = table [I]; e! = Null; e = e. next ){
Object k;
// Determine whether the elements are repeated:
If (e. hash = hash & (k = e. key) = key | key. equals (k) {// first judge whether the Hashcode is the same, and then judge the "=" and equals Methods
V oldValue = e. value;
E. value = value;
E. recordAccess (this );
Return oldValue;
}
}
 
ModCount ++;
AddEntry (hash, key, value, I );
Return null;
}


From this we can see that, in fact, whether the HashSet compares objects is repeated first, it compares the hashcode methods of the two to determine whether they are equal. If they are equal, it compares the equals () method of the object with the "=" method! If no HashCode is equal, equels () and "=" methods will not be compared.
I think the source code is a bit complicated here, because the "=" operator indicates whether the object is the same, since the object is the same (k = e. key) = key returns true, then the expression key. equals (k) must return true. If the object is not the same, that is, (k = e. key) = key returns false, the expression key. equals (k) may still return true.


Let's take a look at how TreeSet is implemented:

First, the underlying data structure of TreeSet is RBTree, which is more efficient. Google is recommended for the specific implementation of the Red/black tree. I am also knowledgeable!
Similarly, we should look at the add () method of Treeset: similarly, we can see the put () method of TreeMap and look at the Code:

[Java]
Public V put (K key, V value ){
Entry <K, V> t = root; // root Node
If (t = null) {// The root node is empty, that is, the first element of map.
// TBD:
// 5045147: (coll) Adding null to an empty TreeSet shold
// Throw NullPointerException
//
// Compare (key, key); // type check
Root = new Entry <K, V> (key, value, null );
Size = 1;
ModCount ++;
Return null;
}
Int cmp;
Entry <K, V> parent;
// Split comparator and comparable paths
Comparator <? Super K> cpr = comparator;
If (cpr! = Null) {// constructor passed in the comparator
Do {
Parent = t;
Cmp = cpr. compare (key, t. key );
If (cmp <0)
T = t. left;
Else if (cmp> 0)
T = t. right;
Else
Return t. setValue (value );
} While (t! = Null );
}
Else {// The constructor does not pass in the comparator. Let's look at the following code!
If (key = null)
Throw new NullPointerException ();
// The object stored in the TreeSet, that is, the key value of the TreeMap, must implement the Comparable interface! Implement the compareTo () method. The value of this method is equal to 0, indicating that the two objects are duplicated !!
Comparable <? Super K> k = (Comparable <? Super K>) key;
Do {
Parent = t;
Cmp = k. compareTo (t. key );
If (cmp <0)
T = t. left;
Else if (cmp> 0)
T = t. right;
Else
Return t. setValue (value); // equal, return!
} While (t! = Null );
}
Entry <K, V> e = new Entry <K, V> (key, value, parent );
If (cmp <0)
Parent. left = e;
Else
Parent. right = e;
FixAfterInsertion (e); // Add a node according to the rules of the red/black tree!
Size ++;
ModCount ++;
Return null;
}


The source code above, I added my own little note! It can be seen that TreeSet and TreeMap determine whether repeated elements are returned Based on the compareTo () method of the object. If the return value is greater than 0, the new node is larger than the original node, and the right branch of the node is stored! The returned value <0 indicates that the new node is smaller than the original node, and the left branch of the node is stored (of course, it will be compared with the left child node )! The return value = 0 indicates that two vertices are repeated.

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.