How Java implements HashMap

Source: Internet
Author: User
Tags addall

1. How Java implements Hashmaphashmap Custom implementation in Java-how HashMap works internally with diagrams and full Program

Http://www.javamadesoeasy.com/2015/02/hashmap-custom-implementation.html

2. HashMap Interview question

in Java, how does HashMap work?

HashMap stores Key-value pairs in the Map.entry static inner class implementation. HashMap uses a hashing algorithm, which uses the hashcode () and Equals () methods in the put and get methods. When we call the Put method by passing Key-value, HashMap uses the key hashcode () and the hashing algorithm to find the index of the stored key-value pair. Entry is stored in LinkedList, so if there is a entry, it uses the Equals () method to check whether the passed key already exists, and if it does, it overwrites value and if it does not, it creates a new entry and then saves it. When we call the Get method by passing the key, it uses hashcode () again to find the index in the array, then uses the Equals () method to find the correct entry, and then returns its value. The following picture explains the details.

Other important questions about HashMap are capacity, load factor, and threshold adjustment. The default initial capacity of the HashMap is 32, and the load factor is 0.75. The threshold is the load factor multiplied by the capacity, whenever we try to add a entry, if the map size is larger than the threshold value, HashMap will re-hash the contents of the map and use a larger capacity. Capacity is always a power of 2, so if you know you need to store a large number of key-value pairs, such as caching data pulled from the database, it's a good idea to initialize the HashMap with the correct capacity and load factor.

What is the importance of the hashcode () and Equals () methods?

HashMap uses the hashcode () and Equals () methods of the Key object to determine the index of the key-value pair. These methods are also used when we try to get the values from the HashMap. If these methods are not implemented correctly, in this case, two different keys may produce the same hashcode () and Equals () outputs, HashMap will think they are the same, then overwrite them instead of storing them in different places. Similarly, all collection classes that do not allow the storage of duplicate data use Hashcode () and Equals () to find duplicates, so it is important to implement them correctly. Implementations of Equals () and hashcode () should follow these rules:

(1) if O1.equals (O2), then o1.hashcode () = = O2.hashcode () is always true.

(2) if o1.hashcode () = = O2.hashcode (), does not mean that o1.equals (O2) will be true.

can we use any class as the key to the map?

We can use any class as the key to the map, but before using them, consider the following points:

(1) If the class overrides the Equals () method, it should also override the Hashcode () method.

(2) all instances of the class need to follow the rules related to equals () and hashcode (). Please refer to these rules as mentioned earlier.

(3) If a class does not use Equals (), you should not use it in Hashcode ().

(4) The best practice for the user-defined key class is to make it immutable, so that the hashcode () value can be cached for better performance. Immutable classes can also ensure that hashcode () and Equals () do not change in the future, which resolves issues related to variability.

For example, I have a class MyKey, which is used in HashMap.

// The name parameter passed to MyKey is used in Equals () and hashcode () New // assume hashcode=1234myhashmap.put (Key, ' Value '); // The following code changes the key's Hashcode () and Equals () values // assume new hashcode=7890 // The following returns NULL because HASHMAP will attempt to find the key that stores the same index, and the key has been changed, the match fails, and the nullmyhashmap.get (' Pankaj ') is returned ("new MyKey") );

That's why string and integer are heavily used as hashmap keys.

what are the different collection views provided by the map interface?

The map interface provides three views of the collection:

(1)set keyset (): Returns a set view of all the keys contained in the map. The collection is supported by map, and map changes are reflected in the collection, and vice versa. When an iterator is traversing a collection, the result of the iterator becomes undefined if the map is modified (except for the removal of the iterator itself). The collection supports element removal through the iterator remove, Set.remove, RemoveAll, Retainall, and clear operations, removing the corresponding mappings from the map. It does not support add and addall operations.

(2)Collection values (): Returns a Collection view of all value contained in a map. This collection is supported by map, and map changes are reflected in the collection, and vice versa. When an iterator is traversing a collection, the result of the iterator becomes undefined if the map is modified (except for the removal of the iterator itself). The collection supports element removal through the iterator remove, Set.remove, RemoveAll, Retainall, and clear operations, removing the corresponding mappings from the map. It does not support add and addall operations.

(3)set<map.entry<k,v>> entryset (): Returns a collection view of all mappings contained in a map clock. This collection is supported by map, and map changes are reflected in the collection, and vice versa. When an iterator is traversing a collection, the result of the iterator becomes undefined if the map is modified (in addition to the iterator's own removal and the entry returned by the iterator). The collection supports element removal through the iterator remove, Set.remove, RemoveAll, Retainall, and clear operations, removing the corresponding mappings from the map. It does not support add and addall operations.

What is the difference between HashMap and Hashtable?

(1)HashMap allows key and value to be null, while Hashtable is not allowed.

(2)Hashtable is synchronous, while HashMap is not. So HashMap is suitable for single-threaded environment, Hashtable is suitable for multi-threaded environment.

(3) A subclass of Linkedhashmap,hashmap is introduced in Java1.4, and if you want to traverse the order, you can easily turn from HashMap to Linkedhashmap, but Hashtable is not, and its order is unpredictable.

(4)HashMap provides a set traversal of key, so it is fail-fast, but Hashtable provides a enumeration traversal of key, which does not support fail-fast.

(5)Hashtable is considered a legacy class, and you should use Cocurrenthashmap if you seek to modify the map during iteration.

How do I decide whether to choose HashMap or TreeMap?

HashMap is the best choice for operations such as inserting, deleting, and locating elements in a map. However, if you need to traverse an ordered set of keys, TreeMap is a better choice. Based on the size of your collection, it may be quicker to add elements to the HashMap, changing the map to TreeMap for an orderly key traversal.

Reference

Http://www.sanesee.com/article/40-java-collections-interview-questions-and-answers

How Java implements HashMap

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.