In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
The main content of this article is to explain "what is the Map interface", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what is the Map interface"?
Map interface
Having studied the Collection interface and its corresponding subinterfaces, we can find that all the data saved in the Collection interface are only a single object, and in the data structure, in addition to saving a single object, it can also be stored in the form of dual objects (key=value), and the core significance of storing binary objects is that you need to obtain the corresponding value through key.
In development, the purpose of Collection collection to save data is to output, and the purpose of Map collection to save data is to find key.
The Map interface is the largest parent interface for saving binary even objects. The interface is defined as follows:
Public interface Map
The interface is an independent parent interface, and the types of Key and Value need to be set when instantiating the interface object, that is, two contents need to be saved during the overall operation. There are many operation methods defined in the Map interface, but the following core operation methods need to be kept in mind:
No. Method name type description 01public V put (K key,V value) general save data to collection 02public V get (Object key) generally convert Map collection to Set collection according to key query data 03public Set entrySet () general query whether the specified key exists 05public Set keySet () generally convert key in Map collection to Set collection 06public V remove (Object key) generally delete specified data according to key
Since JDK1.9, the Map interface has also expanded some static methods for users to use.
Example: observe the characteristics of the Map collection
Import java.util.Map;public class JavaAPIDemo {public static void main (String [] args) throws Exception {/ / Map map=Map.of ("one", 1, "two", 2); / / System.out.println (map); / / {one=1,two=2} / Map map=Map.of ("one", 1, "two", 2, "one", 101); / / System.out.println (map) / / Exception in thread "main" java.lang.IllegalArgumentException: duplicate key: one Map map=Map.of ("one", 1, "two", 2); System.out.println (map); / / Exception in thread "main" java.lang.NullPointerException}}
In the Map collection, the data is stored in the form of "key=value", and the data in the operation using the of () method is not allowed to repeat. If the data is repeated, there will be a "IllegalArgumentException" exception. If the setting content is null, a "NullPointerException" exception will occur.
The of () method seen now is not strictly the standard usage of the Map collection, because normal development requires the instantiation of the interface object through the subclasses of the Map collection, while the commonly used subclasses: HashMap, HashTable, TreeMap, LinkedHashMap.
HashMap subclass
HashMap is the most common subclass in the Map interface. The main feature of this class is unordered storage. First, let's take a look at the definition of the HashMap subclass through the Java document:
Public class HashMap extends AbstractMap implements Map, Cloneable, Serializable
The definition inheritance form of this class is consistent with the previous collection definition form, there are still abstract classes and there is still a need to repeatedly implement the Map interface.
HashMap subclass
Example: observe the use of Map collections
Import java.util.HashMap;import java.util.Map;public class JavaAPIDemo {public static void main (String [] args) throws Exception {Map map = new HashMap (); map.put ("one", 1); map.put ("two", 2); map.put ("one", 101); / / key repeating map.put (null,0); / / key is nullmap.put ("zero", null) / / value is nullSystem.out.println (map.get ("one")); / / key exists: 101System.out.println (map.get (null)); / / key exists: 0System.out.println (map.get ("ten")); / / key does not exist: null}}
The above operation form is the most standard processing form used by the Map collection. Through the code, we can find that the Map interface instantiated by HashMap can save null data for key or value. At the same time, we can also find that even if the key of the saved data is duplicated, then there will be no error, but content replacement.
However, the put () method provided in the Map interface itself provides a return value, so this return value refers to the return of the old value if the key is repeated.
Example: observe the put () method
Import java.util.HashMap;import java.util.Map;public class JavaAPIDemo {public static void main (String [] args) throws Exception {Map map = new HashMap (); System.out.println (map.put ("one", 1)); / / key does not repeat, return null:nullSystem.out.println (map.put ("one", 101); / / key repeat, return old data: 1}}
When the content of the same key is set, the put () method returns the original data content.
Now that you know the basic functions of HashMap, you need to take a look at the source code given in HashMap. HashMap definitely needs to store a lot of data, so for data storage, let's take a look at how HashMap operates:
Public HashMap () {this.loadFactor = DEFAULT_LOAD_FACTOR; / / all other fields defaulted}
When using no-parameter construction, there is a loadFactor property, and the default content of this property is "0.75" (static final float DEFAULT_LOAD_FACTOR = 0.75f;)
Public V put (K key, V value) {return putVal (hash (key), key, value, false, true);}
When using the put () method to save the data, a putVal () method is called, and the key is processed by hash (generating a hash code). For the putVal () method, you will find that a Node node class is provided for data storage, and during the operation using the putVal () method, a resize () method is called to expand the capacity.
Interview question: how to achieve capacity expansion during the put () operation of HashMap?
A constant of "DEFAULT_INITIAL_CAPACITY" is provided in the HashMap class as the initial capacity configuration, and the default size of this constant is 16 elements, that is, the default maximum content that can be saved is 16.
The capacity will be expanded when the saved content exceeds a threshold (DEFAULT_LOAD_FACTOR=0.75f), which is equivalent to "capacity * threshold = 12" when 12 elements are saved.
When carrying on the expansion, HashMap adopts the multiple expansion mode, that is, it expands twice the capacity each time.
Interview question: please explain how HashMap works (started after JDK1.8)
Data storage in HashMap is still done using the Node class, so it is proved that there are only two kinds of data structures that can be used: linked list (time complexity "O (n)") and binary tree (time complexity "O (logn)").
Starting from JDK1.8, the implementation of HashMap has changed, because it has to adapt to the massive data problems of the big data era, so its storage has changed, and there is a constant in the HashMap class: "static final int TREEIFY_THRESHOLD = 8." When using HashMap to save data, if the saved data does not exceed the threshold of 8 (TREEIFY_THRESHOLD), then it will be stored in the form of a linked list, if the threshold is exceeded, the linked list will be converted to a red-black tree to achieve tree balance, and left-handed and right-handed to ensure the query performance of the data.
LinkedHashMap subclass
Although HashMap is the most commonly used subclass in the Map collection, the data saved by it is unordered (orderly or not has no effect on Map). If you want the order of the saved data in the Map collection to increase its order, you can change the subclass to LinkedHashMap (implemented based on the linked list) and observe the definition of the LinkedHashMap class:
Public class LinkedHashMap extends HashMap implements Map
Since it is a linked list, the amount of data should not be particularly large when using the LinkedHashMap class, because it will increase the time complexity. Through the inheritance structure, it can be found that LinkedHashMap is a subclass of HashMap, and the inheritance relationship is as follows:
LinkedHashMap
Example: using LinkedHashMap
Import java.util.LinkedHashMap;import java.util.Map;public class JavaAPIDemo {public static void main (String [] args) throws Exception {Map map = new LinkedHashMap (); map.put ("one", 1); map.put ("two", 2); map.put ("one", 101); map.put ("null", 0); map.put ("zero", null); System.out.println (map); / / {one=101, two=2, null=0, zero=null}
Through the execution of the program at this time, we can find that when using LinkedHashMap for storage, the order in which all data is saved is in the order of adding.
HashTable subclass
The HashTable class is provided from JDK1.0 and belongs to the first batch of dynamic array implementation classes like Vector and Enumeration. Later, in order to retain it, it implements an additional Map interface. The definition of the HashTable class is as follows:
Public class Hashtable extends Dictionary implements Map, Cloneable, Serializable
The inheritance structure of HashTable is as follows:
HashTable subclass
Example: observe the use of the HashTable subclass
Import java.util.Hashtable;import java.util.Map;public class JavaAPIDemo {public static void main (String [] args) throws Exception {Map map = new Hashtable (); map.put ("one", 1); map.put ("two", 2); map.put ("one", 101); / / map.put (null, 0); / / cannot be empty / / map.put ("zero", null) / / cannot be empty, Exception in thread "main" > System.out.println (map); / / {two=2, one=101}
Through observation, it can be found that neither key nor value set for data storage in HashTable is allowed to be null, otherwise a NullPointerException exception will occur.
Interview question: please explain the difference between HashMap and HashTable?
All the methods in HashMap are asynchronous operations and are not thread safe. HashMap allows you to save null data.
HashTable is a synchronous method (thread-safe). HashTable is not allowed to save null, otherwise a NullPointerException exception will occur.
At this point, I believe you have a deeper understanding of "what is the Map interface", might as well come to the actual operation of it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.