Usage of hashmap in Java

Source: Internet
Author: User
Constructor Summary
HashMap()

Construct an empty string with the default initial capacity (16) and default loading Factor (0.75)Hashmap.
HashMap(int initialCapacity)

Construct an empty string with the specified initial capacity and default loading Factor (0.75)Hashmap.
HashMap(int initialCapacity, float loadFactor)

Construct an empty string with the specified initial capacity and loading FactorHashmap.
HashMap(Map<? extends

K,? extends
V> m)

Construct a ing relationship and specifyMapSameHashmap.

Method Summary
 void clear()

Remove all mappings from this ing.
 Object clone()

Return thisHashmapInstance superficial replication: the key and value itself are not cloned.
 boolean containsKey(Object key)

If the ing includes the ing relationship for the specified keyTrue.
 boolean containsValue(Object value)

If this ing maps one or more keys to a specified value, returnTrue.
 Set<Map.Entry<K,V>> entrySet()

Returns the collection view of the ing relationships contained in the ing.
 V get(Object key)

Returns the value mapped by the specified key in the hash ing. If the ing does not contain any ing for this key, the system returnsNull.
 boolean isEmpty()

If the ing does not contain a key-value ing relationshipTrue.
 Set<K> keySet()

Returns the set view of the keys contained in the ing.
 V put(K key,

V value)

In this ing, associate the specified value with the specified key.
 void putAll(Map<? extends

K,? extends
V> m)

Copies all ing relationships of the specified ing to this ing. These ing relationships replace all ing relationships currently targeting all the keys of the specified ing.
 V remove(Object key)

If the ing of the key exists in the ing, delete it.
 int size()

Returns the number of key-value ing relationships in the ing.
 Collection<V> values()

Returns the collection view of the values contained in the ing.
Focuses on hashmap. First, we will introduce what map is. In the array, We index its content through the array subscript, while in the map, we index the object through the object. The object to be indexed is called the key, the corresponding object is value. An example is provided below.

Let's take a look at the differences between hashmap and treemap. Hashmap uses hashcode to quickly search its content, while all elements in treemap maintain a fixed order, if you need to get an ordered result, you should use treemap (the arrangement order of elements in hashmap is not fixed ).

Import java. util. Map;
Import java. util. hashmap;
Import java. util. Set;
Import java. util. hashset;
Import java. util. iterator;
Import java. util. hashtable;
Import java. util. treemap;
Class hashmaps
{
Public static void main (string [] ARGs)
{
Map map = new hashmap ();
Map. Put ("A", "AAA ");
Map. Put ("B", "BBB ");
Map. Put ("C", "CCC ");
Map. Put ("D", "DDD ");

Iterator = map. keyset (). iterator ();
While (iterator. hasnext ()){
Object key = iterator. Next ();
System. Out. println ("map. Get (key) is:" + map. Get (key ));
}

Hashtable tab = new hashtable ();
Tab. Put ("A", "AAA ");
Tab. Put ("B", "BBB ");
Tab. Put ("C", "CCC ");
Tab. Put ("D", "DDD ");
Iterator iterator_1 = tab. keyset (). iterator ();
While (iterator_1.hasnext ()){
Object key = iterator_1.next ();
System. Out. println ("tab. Get (key) is:" + TAB. Get (key ));
}

Treemap TMP = new treemap ();
TMP. Put ("A", "AAA ");
TMP. Put ("B", "BBB ");
TMP. Put ("C", "CCC ");
TMP. Put ("D", "DDD ");
Iterator iterator_2 = TMP. keyset (). iterator ();
While (iterator_2.hasnext ()){
Object key = iterator_2.next ();
System. Out. println ("tmp. Get (key) is:" + TMP. Get (key ));
}

}

}
This is true after execution (hashmap has no order, and treemap is arranged in order !!)

The following is the topic of this article. The following example shows how to use hashmap:

Import java. util .*;

Public class exp1 {
Public static void main (string [] ARGs ){
Hashmap H1 = new hashmap ();
Random R1 = new random ();
For (INT I = 0; I <1000; I ++ ){
Integer T = new INTEGER (r1.nextint (20 ));
If (h1.containskey (t ))
(Ctime) h1.get (t). Count ++;
Else
H1.put (T, new ctime ());
}
System. Out. println (H1 );
}
}

Class ctime {
Int COUNT = 1;
Public String tostring (){
Return integer. tostring (count );
}
}
In hashmap, get () is used to obtain the value, put () is used to insert the value, and containskey () is used to check whether the object already exists. It can be seen that, compared with the arraylist operation, hashmap not only indexes its content through the key, but also has little difference in other aspects.
As mentioned above, hashmap is based on hashcode. There is a hashcode () method in the super-class object of all objects, but it is the same as the equals method and cannot apply to all situations, in this way, we need to rewrite our own hashcode () method. The following is an example:

Import java. util .*;

Public class exp2 {
Public static void main (string [] ARGs ){
Hashmap H2 = new hashmap ();
For (INT I = 0; I <10; I ++)
H2.put (new element (I), new figureout ());
System. Out. println ("H2 :");
System. Out. println ("Get the result for element :");
Element test = new element (5 );
If (h2.containskey (TEST ))
System. Out. println (figureout) h2.get (TEST ));
Else
System. Out. println ("not found ");
}
}

Class element {
Int number;
Public element (int n ){
Number = N;
}
}

Class figureout {
Random r = new random ();
Boolean possible = R. nextdouble ()> 0.5;
Public String tostring (){
If (possible)
Return "OK! ";
Else
Return "impossible! ";
}
}
In this example, the element is used to index the object figureout, that is, the element is the key, and the figureout is the value. A floating point number is randomly generated in figureout. If it is larger than 0.5, print "OK! ", Otherwise print" impossible! ". Then, view the figureout result corresponding to element (5.
The result shows that no matter how many times you run it, the result is "not found ". That is to say, the index element (5) is not in hashmap. How is this possible?

The reason is that the hashcode method of the element inherits from the object, while the hashcode returned by the hashcode method in the object corresponds to the current address, that is, for different objects, even if their content is identical, the values returned with hashcode () are also different. This actually violates our intention. Because when we use hashmap, we want to use the same content of the object index to get the same target object, which requires hashcode () to return the same value at this time. In the preceding example, we expect that the new element (I) (I = 5) and element test = new element (5) are the same, but actually they are two different objects, although they share the same content, they have different addresses in the memory. So naturally, the above program won't get the result we imagined. The following changes to the element class:

Class element {
Int number;
Public element (int n ){
Number = N;
}
Public int hashcode (){
Return number;
}
Public Boolean equals (Object O ){
Return (O instanceof element) & (number = (element) O). number );
} Focuses on hashmap. First, we will introduce what map is. In the array, We index its content through the array subscript, while in the map, we index the object through the object. The object to be indexed is called the key, the corresponding object is value. An example is provided below.

Let's take a look at the differences between hashmap and treemap. Hashmap uses hashcode to quickly search its content, while all elements in treemap maintain a fixed order, if you need to get an ordered result, you should use treemap (the arrangement order of elements in hashmap is not fixed ).

Import java. util. Map;
Import java. util. hashmap;
Import java. util. Set;
Import java. util. hashset;
Import java. util. iterator;
Import java. util. hashtable;
Import java. util. treemap;
Class hashmaps
{
Public static void main (string [] ARGs)
{
Map map = new hashmap ();
Map. Put ("A", "AAA ");
Map. Put ("B", "BBB ");
Map. Put ("C", "CCC ");
Map. Put ("D", "DDD ");

Iterator = map. keyset (). iterator ();
While (iterator. hasnext ()){
Object key = iterator. Next ();
System. Out. println ("map. Get (key) is:" + map. Get (key ));
}

Hashtable tab = new hashtable ();
Tab. Put ("A", "AAA ");
Tab. Put ("B", "BBB ");
Tab. Put ("C", "CCC ");
Tab. Put ("D", "DDD ");
Iterator iterator_1 = tab. keyset (). iterator ();
While (iterator_1.hasnext ()){
Object key = iterator_1.next ();
System. Out. println ("tab. Get (key) is:" + TAB. Get (key ));
}

Treemap TMP = new treemap ();
TMP. Put ("A", "AAA ");
TMP. Put ("B", "BBB ");
TMP. Put ("C", "CCC ");
TMP. Put ("D", "DDD ");
Iterator iterator_2 = TMP. keyset (). iterator ();
While (iterator_2.hasnext ()){
Object key = iterator_2.next ();
System. Out. println ("tmp. Get (key) is:" + TMP. Get (key ));
}

}

}
This is true after execution (hashmap has no order, and treemap is arranged in order !!)

The following is the topic of this article. The following example shows how to use hashmap:

Import java. util .*;

Public class exp1 {
Public static void main (string [] ARGs ){
Hashmap H1 = new hashmap ();
Random R1 = new random ();
For (INT I = 0; I <1000; I ++ ){
Integer T = new INTEGER (r1.nextint (20 ));
If (h1.containskey (t ))
(Ctime) h1.get (t). Count ++;
Else
H1.put (T, new ctime ());
}
System. Out. println (H1 );
}
}

Class ctime {
Int COUNT = 1;
Public String tostring (){
Return integer. tostring (count );
}
}
In hashmap, get () is used to obtain the value, put () is used to insert the value, and containskey () is used to check whether the object already exists. It can be seen that, compared with the arraylist operation, hashmap not only indexes its content through the key, but also has little difference in other aspects.
As mentioned above, hashmap is based on hashcode. There is a hashcode () method in the super-class object of all objects, but it is the same as the equals method and cannot apply to all situations, in this way, we need to rewrite our own hashcode () method. The following is an example:

Import java. util .*;

Public class exp2 {
Public static void main (string [] ARGs ){
Hashmap H2 = new hashmap ();
For (INT I = 0; I <10; I ++)
H2.put (new element (I), new figureout ());
System. Out. println ("H2 :");
System. Out. println ("Get the result for element :");
Element test = new element (5 );
If (h2.containskey (TEST ))
System. Out. println (figureout) h2.get (TEST ));
Else
System. Out. println ("not found ");
}
}

Class element {
Int number;
Public element (int n ){
Number = N;
}
}

Class figureout {
Random r = new random ();
Boolean possible = R. nextdouble ()> 0.5;
Public String tostring (){
If (possible)
Return "OK! ";
Else
Return "impossible! ";
}
}
In this example, the element is used to index the object figureout, that is, the element is the key, and the figureout is the value. A floating point number is randomly generated in figureout. If it is larger than 0.5, print "OK! ", Otherwise print" impossible! ". Then, view the figureout result corresponding to element (5.
The result shows that no matter how many times you run it, the result is "not found ". That is to say, the index element (5) is not in hashmap. How is this possible?

The reason is that the hashcode method of the element inherits from the object, while the hashcode returned by the hashcode method in the object corresponds to the current address, that is, for different objects, even if their content is identical, the values returned with hashcode () are also different. This actually violates our intention. Because when we use hashmap, we want to use the same content of the object index to get the same target object, which requires hashcode () to return the same value at this time. In the preceding example, we expect that the new element (I) (I = 5) and element test = new element (5) are the same, but actually they are two different objects, although they share the same content, they have different addresses in the memory. So naturally, the above program won't get the result we imagined. The following changes to the element class:

Class element {
Int number;
Public element (int n ){
Number = N;
}
Public int hashcode (){
Return number;
}
Public Boolean equals (Object O ){
Return (O instanceof element) & (number = (element) O). number );
}
}
Here, element overwrites the hashcode () and equals () methods in the object. Overwrite hashcode () so that it returns the value of number as hashcode, so that their hashcode is the same for objects with the same content. Overwrite equals () is used to make the result meaningful when hashmap judges whether two keys are equal (related to rewriting equals () for more information, see my another article "re-compile methods in the object class". The modified program running result is as follows:
H2:
Get the result for element:
Impossible!

Remember: If you want to use hashmap effectively, you must overwrite it in its hashcode (). There are two principles for rewriting hashcode:

You don't have to generate a unique hashcode for each different object, as long as your hashcode method enables get () to get the content put in put. That is, "Not one principle ". The hashcode generation algorithm tries its best to make the hashcode values more scattered, rather than a lot of hashcode is concentrated in a range, which is conducive to improving the performance of hashmap. That is, the "Decentralization principle ".
}
Here, element overwrites the hashcode () and equals () methods in the object. Overwrite hashcode () so that it returns the value of number as hashcode, so that their hashcode is the same for objects with the same content. Overwrite equals () is used to make the result meaningful when hashmap judges whether two keys are equal (related to rewriting equals () for more information, see my another article "re-compile methods in the object class". The modified program running result is as follows:
H2:
Get the result for element:
Impossible!

Remember: If you want to use hashmap effectively, you must overwrite it in its hashcode (). There are two principles for rewriting hashcode:

You don't have to generate a unique hashcode for each different object, as long as your hashcode method enables get () to get the content put in put. That is, "Not one principle ". The hashcode generation algorithm tries its best to make the hashcode values more scattered, rather than a lot of hashcode is concentrated in a range, which is conducive to improving the performance of hashmap. That is, the "Decentralization principle ".

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.