Reprinted from: http://blog.csdn.net/tomholmes7/article/details/2663379. Reprint please indicate the original author's address
Map
Map stores data in the form of key/numeric pairs, and arrays are very similar to the indexes that exist in the array, which are themselves objects.
The interface of Map
map---Implementation Map
The inner class of the map.entry--map that describes the key/value pairs in the map.
SortedMap---Extend the map to keep the keys in ascending order
In terms of how to use it, it is generally a subclass of the map, rather than using the map class directly.
Let's take hashmap as an example. Full code
Packagetest_map123;ImportJava.util.HashMap;ImportJava.util.Iterator;ImportJava.util.Map;ImportJava.util.Set; Public classTest_map {@SuppressWarnings ("Rawtypes") Public Static voidMain (String args[]) {HashMap<string, string> HashMap =NewHashmap<string, string>(); Hashmap.put ("Item0", "Value0"); Hashmap.put ("Item1", "Value1"); Hashmap.put ("Item2", "Value2"); Hashmap.put ("Item3", "Value3"); Set Set=Hashmap.entryset (); Iterator Iterator=Set.iterator (); while(Iterator.hasnext ()) {Map.entry Mapentry=(Map.entry) iterator.next (); System.out.println (Mapentry.getkey ()+ "/" +Mapentry.getvalue ()); } }}
View Code
Results:
Item1/value1
Item2/value2
Item0/value0
Item3/value3
Note that the keys to this map must be unique, such as the inability to have two keys null.
If you use it, you will know its usefulness.
Another example:
map<string, order> map = new hashmap<string, order> ();
Map.put ("Order", (order) obj);
Information:
The collection container contains the set and list interfaces, and the set contains the LinkedList and ArrayList in the Hashset,list, and only the HashMap in a separate map interface.
The collection classes in Java. util contain some of the most commonly used classes in Java . The most common collection classes are List and Map. The specific implementation of the list includes ArrayList and vectors, which are variable-sized lists that are more appropriate for building, storing, and manipulating any type of object. The List is useful for cases where elements are accessed by numeric indexes, where the data is sequential and repeatable. The data in set is not sequential and cannot be duplicated.
MAP provides a more general method of storing elements. The Map collection class is used to store element pairs (called "Keys" and "values"), where each key is mapped to a value. Conceptually, you can treat a List as a Map with numeric keys. In fact, in addition to the List and Map are in the definition of Java. Util there is no direct link between the two countries. This article will focus on the map included with the core Java Distribution Suite, and will also show you how to adopt or implement a dedicated map that is more appropriate for your application-specific data.
Understanding MAP Interfaces and methods
There are many predefined Map classes in the Java core class. Before we introduce the implementation, let's start by introducing the Map interface itself to understand the common denominator of all implementations. The map interface defines four types of methods, each of which is contained by each map. Below, we'll start by introducing these methods from two common methods ( table 1).
Table 1: Overridden methods. We cover these two methods of this object to correctly compare the equivalence of the Map object.
Equals (Object o) |
Compare the equivalence of a specified object to this Map |
Hashcode () |
Returns the hash code for this MAP |
MAP Build
Map defines several transformation methods for inserting and deleting elements ( table 2).
Table 2:map Update method: You can change the Map content.
Clear () |
Remove all mappings from the map |
Remove (Object key) |
Remove keys and associated values from a Map |
Put (object key, Object value) |
Associate a specified value with a specified key |
Clear () |
Remove all mappings from the map |
Putall (Map t) |
Copies all mappings in the specified map to this map |
Although you may notice that even assuming that the cost of building a Map that needs to be passed to Putall () is ignored, using Putall () is not usually more efficient than using a large number of put () calls, but the existence of Putall () is not uncommon. This is because Putall () needs to iterate over the elements of the map passed, in addition to the algorithm that the iteration put () does to add each key-value pair to the map. It should be noted, however, that Putall () can correctly resize the map before adding all the elements, so if you do not adjust the size of the map yourself (which we will briefly describe), Putall () may be more efficient than expected.
View Map
The elements in the iteration Map do not have a straightforward method. If you are querying a map to see which elements satisfy a particular query, or if you want to iterate over all of its elements, regardless of the cause, you first need to get the view of the map. There are three possible views (see table 3)
- All key-value pairs-see EntrySet ()
- All keys-see KeySet ()
- All values-see values ()
The first two views return a Set object, and the third view returns the Collection object. In both cases, the problem does not end here because you cannot iterate directly over the Collection object or the Set object. To iterate, you must obtain a Iterator object. Therefore, to iterate over the elements of the MAP, it is necessary to do a cumbersome coding
Iterator keyvaluepairs = Amap.entryset (). Iterator (); Iterator keys = Amap.keyset (). Iterator (); Iterator values = Amap.values (). iterator ();
It is worth noting that these objects (Set, Collection, and Iterator) are actually views of the underlying Map, rather than a copy of all the elements. This makes them highly efficient to use. On the other hand, the ToArray () method of the Collection or Set object creates an array object that contains all the elements of the MAP, so it is not efficient except in cases where the elements in the array are really needed.
I ran a small test ( Test1in the accompanying file) that used HashMap and compared the cost of the iteration Map element using the following two methods:
int mapsize = Amap.size (); Iterator keyValuePairs1 = Amap.entryset (). Iterator (); for (int i = 0; i < mapsize; i++) { map.entry Entry = (map.entry) keyvaluepairs1.next (); objec T key = Entry.getkey (); Object value = Entry.getvalue (); ...} object[] keyValuePairs2 = Amap.entryset (). ToArray (); for (int i = 0; i < REM; i++) {{ map.entry Entry = (map.entry) keyvaluepairs2[i]; Object key = Entry.getkey ();
profilers in Oracle JDeveloper Oracle JDeveloper includes an embedded monitor that measures memory and execution time, enabling you to quickly identify bottlenecks in your code. I used Jdeveloper's execution monitor to monitor the HashMap containskey() and Containsvalue () methods, and soon discovered that the ContainsKey() method was faster than Contai The Nsvalue () method is much slower (actually a few orders of magnitude slower!). )。 (see Figure 1 and Figure 2, and the Test2 class in the accompanying file). |
Object value = Entry.getvalue (); ...}
This test uses two methods of measurement: one is to measure the time of an iterative element, and the other is to measure the additional overhead of creating an array using the ToArray call. The first method (ignoring the time it takes to create an array) indicates that an array iteration element that has been created from the ToArray call is about 30%-60% faster than the Iterator. But if the cost of creating an array using the ToArray method is included, then using Iterator is actually 10%-20% faster. Therefore, if for some reason you want to create an array of collection elements instead of iterating over those elements, you should use that array to iterate over the elements. But if you do not need this intermediate array, do not create it, but instead use the Iterator iteration element.
Table 3: Return to the Map method of the view: Using the objects returned by these methods, you can traverse the elements of the map, and you can also delete the elements in the map.
EntrySet () |
Returns the Set view of the map contained in the map. Each element in the Set is a Map.entry object that can be accessed using the GetKey () and GetValue () methods (and a SetValue () method) to access the key and value elements of the latter |
KeySet () |
Returns the Set view of the key contained in the MAP. Deleting the elements in the set also deletes the corresponding mappings (keys and values) in the map |
VALUES () |
Returns a Collection view of the values contained in the map. Deleting the elements in Collection also deletes the corresponding mappings (keys and values) in the map |
accessing elements
The Map access method is listed in table 4. A Map is generally suitable for keystrokes (rather than by value) for access. The MAP definition does not stipulate that this is certainly true, but usually you can expect this to be true. For example, you can expect the ContainsKey() method to be as fast as the Get () method. On the other hand, the Containsvalue () method is likely to need to scan the values in the Map, so it may be slower.
Table 4:map Access and test methods: These methods retrieve information about the map content but do not change the map content.
Get (Object key) |
Returns the value associated with the specified key |
ContainsKey (Object key) |
Returns TRUE if the map contains a mapping of the specified key |
Containsvalue (Object value) |
Returns TRUE if this map maps one or more keys to a specified value |
IsEmpty () |
Returns true if map does not contain a key-value mapping |
Size () |
Returns the number of key-value mappings in a map |
Testing for the time required to traverse all elements in the HASHMAP using containskey() and Containsvalue () indicates that Containsvalue () takes much longer. It actually takes a few orders of magnitude! (see Figure 1 and Figure 2, as well as the Test2in the accompanying file). Therefore, if Containsvalue () is a performance issue in the application, it will soon appear and can be easily identified by monitoring your application. In this case, I believe you can come up with an effective replacement method to implement the equivalent functionality provided by Containsvalue (). But if you can't figure out a way, a workable solution is to create a map and use all the values of the first map as keys. Thus, the Containsvalue () on the first map will be the more efficient containskey() on the second map.
Use of Java _map interface (reprint)