Map of the Java Collection framework

Source: Internet
Author: User
Tags delete key int size random seed rehash shallow copy

Map

Map is a container that associates key objects with value objects

A value object can also be a map, and so on, so that a multilevel mapping can be formed. For a key object, like set, a key object in a map container does not allow repetition, which is to keep the consistency of the search results , and if there are two key objects, then there is a problem when you want to get the value object corresponding to that key object, and you may not get the value object you want. The result is confusion, so the uniqueness of the key is important and conforms to the nature of the set. Of course, in the process of use, the value object corresponding to a key may change, then the last modified value object corresponds to the key. there is no unique requirement for value objects . You can map any number of keys to a value object without any problems (though it may be inconvenient for you to use it, you don't know what you get is the value object for that key). There are two more common implementations of map: HashMap and TreeMap. HashMap also uses the hash code algorithm, in order to quickly find a key , TreeMap is the key in order to store , so it has some extension methods, such as Firstkey (), Lastkey (), etc., You can also specify a range from TreeMap to get its child map. The association of Keys and values is simple, and a key can be associated with a value object using the put (Object Key,object value) method. Use Get (object key) to get the value object corresponding to this key object.

function of Map

ArrayList allows you to choose a number in a sequence of objects, so in a sense it is associating numbers with objects. But what if you want to choose from a sequence of objects based on other criteria? The stack is an example. Its standard is "pick the last object to be pushed into the stack." Our common terminology, map,dictionary, or associative array, is a very powerful tool that can be selected within a sequence. Conceptually, it looks like a ArrayList, but instead of a number, it uses another object to find the Object! This is a crucial programming skill . (is a map, the key is somewhat similar to the primary key of the database, the value is somewhat similar to the corresponding table)

This concept is represented in Java as a map. The Put (object key, Object value) method will add a value to the map and associate the value with the key (the object you are looking for). When the key is given, the get (Object key) returns the value associated with it. You can also use ContainsKey () and Containsvalue () to test if a map contains a key or value.

There are several types of map:hashmap,treemap,linkedhashmap,weakhashmap in the Java Standard Class Library, as well as Identityhashmap. They all implement the basic interface of map, but there is a clear surprise in the way of behavior. These differencing bodies now, efficiency, hold and represent the order of the pair, the length of time the object is held, and how to determine the equality of the keys.

Performance is a big problem that map has to face. If you know how to work with get (), you will find that (for example) finding objects in ArrayList can be quite slow. And that's what HashMap's strength is. Instead of slowly looking for the key, it uses a special value called hash code (hashcode specifically see: http://blog.csdn.net/qq_23473123/article/details/51111323) to find it. Hash (hash) is an algorithm that extracts some information from the target object and then generates an int that represents the "relative uniqueness" of the object. Hashcode () is a method of the object root class, so all Java objects can generate hash code. HashMap uses the object's Hashcode () to find it quickly. This has dramatically improved performance.

Map (interface): maintains the key-value relationship (both pairs) so that the key can be used to find the value.

HashMap

: HashMap is a hash table that stores content that is a key-value pair (key-value) mapping.
HashMap inherits from Abstractmap, and realizes the map, cloneable, java.io.Serializable interface.

the implementation of the HASHMAP is not synchronous, which means it is not thread-safe . Both its key and value can be null. In addition, the mappings in HashMap are not ordered.
An instance of HashMap has two parameters that affect its performance:initial capacity and load factor. Capacity is the number of buckets in the hash table, and the initial capacity is just the capacity at the time of creation of the Hashtable. A load factor is a scale in which a hash table can reach a full amount before its capacity increases automatically. When the number of entries in the hash table exceeds the product of the load factor with the current capacity, the Hashtable is rehash (that is, rebuilding the internal data structure)so that the Hashtable will have about twice times the number of buckets.

Typically, the default load factor is 0.75, which is a tradeoff in time and space costs. The high load factor, while reducing the space overhead, also increases the query cost (which is reflected in the operations of most HASHMAP classes, including get and put operations). When setting the initial capacity, you should take into account the number of entries required in the mapping and their loading factors to minimize the number of rehash operations. The rehash operation does not occur if the initial capacity is greater than the maximum number of entries divided by the load factor.

HashMap's inheritance Relationship:

HashMap and map relationships such as:

code example:

Import Java. Util. Map;Import Java. Util. Random;Import Java. Util. Iterator;Import Java. Util. HashMap;Import Java. Util. HashSet;Import Java. Util. Map. Entry;Import Java. Util. Collection;public class Hashmaptest {public static void main (string[] args) {Testhashmapapis ();} private static void Testhashmapapis () {//Initialize random seed randomly r = new Random ();New HashMap HashMap map = new HashMap ();Add Action Map. Put("One"R. Nextint(Ten));Map. Put("both"R. Nextint(Ten));Map. Put("three"R. Nextint(Ten));Print out the map System. out. println("Map:"+MAP);Traverse Key-value Iterator iter via Iterator = map. EntrySet(). Iterator();while (ITER. Hasnext()) {Map. EntryEntry = (Map. Entry) ITER. Next();System. out. println("Next:"+ Entry. GetKey() +" - "+entry. GetValue());}//HashMap number of key-value pairs System. out. println("Size:"+map. Size());ContainsKey (Object Key): Whether the key is included in the System. out. println("contains key:"+map. ContainsKey("both"));System. out. println("contains key five:"+map. ContainsKey("Five"));Containsvalue (Object value): Whether it contains the value of the System. out. println("contains value 0:"+map. Containsvalue(New Integer (0)));Remove (Object key): Delete key key corresponding to map. Remove("three");System. out. println("Map:"+MAP);Clear (): Empty HashMap Map. Clear();IsEmpty (): HashMap is empty System. out. println(Map. IsEmpty()?"Map is empty":"Map is not empty") );}}
Hashtable

The main difference between Hashtable and HashMap is that Hashtable is thread-synchronized, except that Hashtable does not allow NULL values and NULL keys.

Linkedhashmap

: Much like HashMap, but when traversing with iterator, it is accessed in the order in which it was inserted or in the order in which it was first used (least-recently-used (LRU) . In addition to using iterator, in other cases, just a little slower than HashMap.

Linkedhashmap (int initialcapacity, float loadfactor, Boolean accessorder)

Summary of construction methods and methods:

Initialcapacity-Initial capacity
Loadfactor-load factor
Accessorder-Sort mode-true for the access order, or FALSE for the insertion order

When Accessorder is false:
Whenever an element is accessed, the element is moved from its current position to the end of the list, so we can see that the element that is closer to the beginning of the list uses the least, which is the legendary " least recent principle ", which is very useful for caching, for example, We may want to put the most frequently accessed elements into the cache, and the elements that are not long to be accessed into the database.

Example code:

ImportJava.util.LinkedHashMap;ImportJava.util.Map;ImportJava.util.Random;ImportJava.util.concurrent.ConcurrentLinkedQueue; Public  class linkedhashmaptest {     Public Static void Main(string[] args) {Linkedhashmap<integer, people> map =NewLinkedhashmap<integer, People> ( -, (float)0.75,false); People p1 =NewPeople ("Robin.",1, -); People p2 =NewPeople ("Robin.",2, in); People p3 =NewPeople ("Harry.",3, -); Map.put (NewInteger ( -), p1); Map.put (NewInteger (1), p3); Map.put (NewInteger (2),NULL); Map.put (NewInteger ( -), p2); for(People p:map.values ()) {System.out.println ("People:"+ p); }}}class people {String name;intIdintAge Public people(String name,intID) { This(Name, ID,0); } Public people(String name,intIdintAge) { This. name = name; This. id = ID; This. Age = Age; } PublicStringtoString() {returnID + name + age; } Public Boolean equals(Object o) {if(O = =NULL)return false;if(! (OinstanceofPeople))return false; People p = (people) O;Booleanres = name.equals (p.name);if(RES) System.out.println ("Name"+ name +"is double");ElseSYSTEM.OUT.PRINTLN (name +"VS"+ p.name);returnRes } Public int hashcode() {returnName.hashcode (); }}

Note that this implementation is not synchronous. If more than one thread accesses the linked hash map at the same time, and at least one of the threads modifies the mapping from the structure, it must remain externally synchronized. This is typically done by synchronizing the objects that naturally encapsulate the mapping. If such an object does not exist, you should use the Collections.synchronizedmap method to "wrap" the map. It is best to do this at the time of creation to prevent unintended non-synchronous access to the mappings:

 Map m = Collections.synchronizedMap(new LinkedHashMap(...));
TreeMap

: Based on the implementation of red-black tree data structure. When you look at a key or pair, you'll see that they are arranged in order (according to comparable or comparator). The TreeMap feature is that what you get is an ordered map. TreeMap is the only implementation of the map with the Submap () method. This method allows you to get a portion of the tree.

Construction Method:

Method Summary:

 Map. entry<K,v> Ceilingentry (KKey) returns a key-value mapping relationship that is associated with a minimum key greater than or equal to the given key, or null if no such key exists.KCeilingkey (KKey) returns the minimum key greater than or equal to the given key, or null if no such key exists. void Clear () Removes all mapping relationships from this mapping. Object Clone () returns a shallow copy of this TREEMAP instance. comparator<? SuperK> Comparator () returns a comparer that sorts the keys in this map and returns NULL if the map uses the natural order of the keys. Boolean ContainsKey (Object key) returns True if this map contains a mapping relationship for the specified key. Boolean Containsvalue (Object value) returns True if this mapping maps one or more keys for the specified value. navigableset<K> Descendingkeyset () returns an inverted navigableset view of the keys contained in this map. navigablemap<K,v> Descendingmap () returns an inverted view of the mappings contained in this map.Set<Map. entry<K,v>> EntrySet () returns the mapping relationships contained in this map.SetView.Map. entry<K,v> Firstentry () returns a key-value mapping relationship that is associated with the minimum key in this map, or null if the mapping is empty.KFirstkey () returns the current first (lowest) key in this map.Map. entry<K,v> Floorentry (KKey) returns a key-value mapping relationship that is associated with a maximum key that is less than or equal to the given key, or null if no such key exists.KFloorkey (KKey) returns the maximum key that is less than or equal to the given key, or null if no such key exists. V get (Object key) returns the value mapped by the specified key, or null if the map does not contain any mapping relationships for that key. sortedmap<K,v> Headmap (KTokey) Returns a partial view of this map whose key value is strictly less than tokey. navigablemap<K,v> Headmap (KTokey, Boolean inclusive) returns a partial view of this map whose key is less than (or equal to, if inclusive is true) Tokey.Map. entry<K,v> Higherentry (KKey) returns a key-value mapping relationship that is associated with a minimum key that is strictly greater than the given key, or null if no such key exists.KHigherkey (KKey) returns the minimum key that is strictly greater than the given key, or null if no such key exists.Set<K> KeySet () returns the key that this map contains.SetView.Map. entry<K,v> Lastentry () returns the key-value mapping relationship associated with the largest key in this map, or null if the mapping is empty.KLastkey () returns the last (highest) key currently in the map.Map. entry<K,v> Lowerentry (KKey) returns a key-value mapping relationship that is associated with a maximum key that is strictly less than the given key, or null if no such key exists.KLowerkey (KKey) returns the maximum key that is strictly less than the given key, or null if no such key exists. navigableset<K> Navigablekeyset () returns the Navigableset view of the keys contained in this map.Map. entry<K,v> pollfirstentry () removes and returns the key-value mapping relationship associated with the smallest key in this map, or null if the mapping is empty.Map. entry<K,v> polllastentry () removes and returns the key-value mapping relationship associated with the largest key in this map, or null if the mapping is empty. V put (KKey, V value) associates the specified value with the specified key in this map. void Putall (Map<? ExtendsK,? Extends v> map) copies all mappings in the specified map to this map. V Remove (Object key) If there is a mapping relationship for the key in this TreeMap, delete it. an int size () returns the number of key-value mapping relationships in this map. navigablemap<K,v> SubMap (KFromkey, Boolean frominclusive,KTokey, Boolean toinclusive) returns a partial view of this map whose keys range from Fromkey to Tokey. sortedmap<K,v> SubMap (KFromkey,KTokey) Returns a partial view of this map whose key values range from Fromkey (including) to Tokey (not included). sortedmap<K,v> Tailmap (KFromkey) Returns a partial view of this map whose key is greater than or equal to Fromkey. navigablemap<K,v> Tailmap (KFromkey, Boolean inclusive) returns a partial view of this map whose key is greater than (or equal to, if inclusive is true) Fromkey. Collection<v> values () returns the Collection view of the values that this map contains.
Identityhashmap

In HashMap, it uses the Equals method to determine whether the two keys are equal, and in Identityhashmap, it uses = = To determine whether the two keys are equal. Besides, it's no different from HashMap.

SortedMap

SortedMap (only treemap this one implementation) key is definitely orderly, so there are some additional functions in this interface method.

Method table:

Map of the Java Collection framework

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.