Reprinted: http://blog.sina.com.cn/s/blog_6e10b9110100qiuz.html
The complexity of containskey is O (1). It calculates the hashcode directly based on the given parameter key to see if there is any related location. If the location is occupied, search for the next location. The following is the main code for JDK to implement containskey: int hash = hash (k); int I = indexfor (hash, table. length); entry E = table [I]; while (E! = NULL) {If (E. hash = hash & eq (K, E. key) return true; E = E. next;} containsvalue's complexity is O (n). For hashmap, value depends on the key, so it can only traverse the entire set. The main code for JDK implementation is as follows: entry [] tab = table; For (INT I = 0; I <tab. length; I ++) for (Entry E = tab [I]; e! = NULL; E = E. Next) if (value. Equals (E. Value) return true; return false;
Two Methods of hashmap Traversal
First:
Map map = new hashmap ();
Iterator iter = map. entryset (). iterator ();
While (ITER. hasnext ()){
Map. Entry entry = (Map. Entry) ITER. Next ();
Object key = entry. getkey ();
Object val = entry. getvalue ();
}
High efficiency. You must use this method in the future!
Second:
Map map = new hashmap ();
Iterator iter = map. keyset (). iterator ();
While (ITER. hasnext ()){
Object key = ITER. Next ();
Object val = map. Get (key );
}
Low efficiency. Try to use less in the future!
Example:
There are two common methods for hashmap traversal: Using keyset and entryset for traversal, but the traversal speed of the two is different. See the example below:
Public class hashmaptest {
Public static void main (string [] ARGs )...{
Hashmap = new hashmap ();
For (INT I = 0; I <1000; I )...{
Hashmap. Put ("" I, "thanks ");
}
Long BS = calendar. getinstance (). gettimeinmillis ();
Iterator = hashmap. keyset (). iterator ();
While (iterator. hasnext ())...{
System. Out. Print (hashmap. Get (iterator. Next ()));
}
System. Out. println ();
System. Out. println (calendar. getinstance (). gettimeinmillis ()-BS );
Listhashmap ();
}
Public static void listhashmap ()...{
Java. util. hashmap = new java. util. hashmap ();
For (INT I = 0; I <1000; I )...{
Hashmap. Put ("" I, "thanks ");
}
Long BS = calendar. getinstance (). gettimeinmillis ();
Java. util. iterator it = hashmap. entryset (). iterator ();
While (it. hasnext ())...{
Java. util. Map. Entry entry = (Java. util. Map. Entry) it. Next ();
// Entry. getkey () returns the key corresponding to this item.
// Entry. getvalue () returns the value corresponding to this item.
System. Out. Print (entry. getvalue ());
}
System. Out. println ();
System. Out. println (calendar. getinstance (). gettimeinmillis ()-BS );
}
}
The keyset is actually traversed twice. Once converted to iterator, the key pair value is retrieved from the hashmap at one time. However, entryset only traverses the data for the first time. It puts both the key and value into the entry, so it's faster.
Note: The hashtable Traversal method is similar to the above one!