The map class in Java uses

Source: Internet
Author: User
Tags map class set set

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.
public static void Main (String args[])
{
HashMap HashMap = new HashMap ();
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 ());
}
}
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 class in Java.util contains 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 and foreign, there is no direct link between the two. 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) compares the equivalence of the 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 () Removes all mappings from the map
Remove (Object key) removes the key and associated values from the Map
Put (object key, Object value) relates the specified value to the specified key
Clear () Removes 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 (Test1 in the accompanying file) that used HashMap and compared the cost of the iteration Map element using the following two methods:

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's ContainsKey () and Containsvalue () methods, and soon discovered that the ContainsKey () method was much slower than the Containsvalue () method (actually Take a few orders of magnitude slower! )。 (see Figure 1 and Figure 2, and the Test2 class in the accompanying file).

int mapsize = Amap.size (); Iterator keyValuePairs1 = Amap.entryset (). Iterator (); for (int i = 0; i < mapsize; i++) {Ma    P.entry Entry = (map.entry) keyvaluepairs1.next ();    Object key = Entry.getkey ();    Object value = Entry.getvalue (); ...} object[] keyValuePairs2 = Amap.entryset (). ToArray (); for (int i = 0; i < REM; i++) {{Map.entry Entry = (map.entry) k    Eyvaluepairs2[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's ContainsKey () and Containsvalue () methods, and soon discovered that the ContainsKey () method was much slower than the Containsvalue () method (actually Take 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

Www.2cto.com


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 the 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 Test2 in 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.

The map class in Java uses

Related Article

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.