Java Collection Framework summary (5) use of The--map interface

Source: Internet
Author: User
Tags comparable set set

Java Collection Framework summary (5) use of The--map interface

Map is used to hold data that has a mapping relationship (key-vlaue). The key of map does not allow repetition, that is, any two key of the same map object is always returned false by the Equals method

The map contains a keyset () method that returns a set set of map so that key is Composed.

The map collection is similar to the storage of set elements, such as hashset, linkedhashset, SortedSet (interface), TreeSet, enumset, and so on, while the map interface has hashmap, linkedhashmap, sortedmap (interface), TreeMap, enummap, and other implementation classes and Sub-interfaces.

The value of map is very similar to the list: elements can be duplicated between elements, and each element can be found based on the index (key).

Maps are sometimes referred to as dictionaries, or associative arrays.

The map interface defines the following methods:

    • Void Clear (); Delete all key-value pairs in the map Object.
    • Boolean ContainsKey (Object key): queries whether the map contains the specified key and returns True if it is Included.
    • Boolean Containsvalue (Object value): queries whether the map contains one or more value, and returns True if it is Included.
    • Set EntrySet (): Returns the set set of all contained key-value pairs in the map, each of which is Map.entry (Entry is the inner class of the Map) Object.
    • Object Get (obejct key): returns the value corresponding to the specified key, or null if no key is included in this map.
    • Boolean isEmpty (): queries whether the map is empty (that is, does not contain any Key-value Pairs) and returns True if it is Empty.
    • Set KeySet (): Returns the set set of all keys in the map.
    • Object put (object key, object value): Add a key-value pair, and if there is already a key-value pair in the current map that is equal to that key, the new Key-value pair will overwrite the original Key-value pair.
    • Object Remove (object key): removes the key-value pair corresponding to the specified key, returns the value associated with the deleted key, or null if the key does not exist.
    • int size (): Returns the number of key-value pairs in the map.
    • Collection values (): Returns the Collection of all value components in the MAP.

The map interface provides a large number of implementation classes, such as HashMap and hashtable, as well as the subclass Linkedhashmap of hashmap, and the SortedMap Sub-interface and the implementation class treemap of the Interface. The details are described below.

The map includes an inner class: Entry. This class encapsulates a key-value pair, and entry contains three Methods:

    • Object getkey (): Returns the key value contained in the Entry.
    • Object getValue (): Returns the value contained in the Entry.
    • Object setValue (): Sets the value contained in the entry and returns the value of the new Setting.

The map can be understood as a special set, except that the set contains the set elements that are entry objects, not ordinary Objects.

1, HashMap and Hashtable implementation class

HashMap and Hashtable are both implementation classes of the map interface, Hashtable is an ancient map implementation class, which has been available since JDK1.0, and contains two cumbersome methods: elements () (similar to the map interface definition of values () METHOD) and Keys () (similar to the keyset () method defined by the map interface), These two methods are now seldom used.

Two points difference:

    • Hashtable is a thread-safe map implementation, but HashMap is a thread-insecure implementation, so HashMap is more powerful than hashtable, but if you are accessing the same map object in multiple threads, it is better to use the Hashtable implementation class.
    • Hashtable does not allow NULL as key and value, and if null, throws an NullPointerException exception, but HashMap can use NULL as key or Value.

Because HashMap can not be repeated, so there is only a pair of hashmap in the Key-value value is null, but there can be countless multiple key-value pairs of value is Null.

HashMap overrides the ToString () method method to always return a string in the following format: {key1 = Value1,key2 = value2 ...}

HashMap, Hashtable judge two keys equal to the standard is: two key by Equasl method to compare return ture, two key hashcode value is Equal.

Linkedhashmap class

HashMap has a subclass: linkedhashmap, which is also a doubly linked list to maintain the order of Key-value pairs, which defines the order of iterations, which is consistent with the order in which key-value pairs are Inserted.

Linkedhashmap can avoid sorting key-value pairs in hashmap, Hashtable (as long as the key-value pair is inserted in order). At the same time, you can avoid the increased cost of using treemap.

Linkedhashmap needs to maintain the insertion order of the elements, so performance is slightly lower than hashmap performance, but it will perform well when iterating through all the elements of the map, because it maintains the internal order in the List.

Properties Class

The properties class is a subclass of the Hashtable class that handles property files, such as the INI file on the Windows operating platform. The properties class can associate a map object with a property file so that the key-value pair in the Map object can be written to the property file, or the property name = attribute value in the property file can be loaded into the map Object. Because property names and property values in property files can only be string types, key and value in properties are string types that provide the following three ways to modify the key and value values in Properties.

    1. String GetProperty (string key): Gets the property value corresponding to the property name specified in properties, similar to the Get (Object Key) method of Map.
    2. String GetProperty (string key, String defaultvalue): This method is basically similar to the previous Method. This method has one more function and returns a default value if the specified key does not exist in the Properties.
    3. Object geproperty (string key, string value): sets the property value, similar to the Hashtable put Method.

Provides a method for two read and write properties files:

    1. void load (inputstream instream): loads the property name = property value from the property file (represented in the input stream), appends the loaded property name = property value pair to the Properties (because properties are hashtable), It does not guarantee the order between the Key-value pairs).
    2. void Store (outputstream out, String comment): writes the Key-valu pair in properties to the specified properties file (expressed in the output stream).

Sample Program:

public class Testproperties{public    static void main (string[] Args) throws Exception    {        Properties props = new Properties ();        Add attribute Props.setproperty to properties        ("username", "yeeku");        Props.setproperty ("password", "123456");        Save attributes in properties to the A.ini file        props.store (new fileoutputstream ("a.ini"), "comment line");        Create a new Properties Object        Properties Props2 = new properties ();        Add attribute Props2.setproperty to properties        ("gender", "male");        Append the attribute Name-property value in the A.ini file to props2 in        props2.load (new fileinputstream ("a.ini"));        System.out.println (props2);    }}

Operation Result:

{password=123456, gender=male, username=yeeku}

2. SortedMap Interface and TREEMAP implementation class

The map interface derives a sortedmap Sub-interface and TreeMap implements the class for it. Similar to the TreeSet sort, TreeMap is also based on the Red-black tree to sort all the keys in the treemap, ensuring that all key-value pairs in the treemap are in an orderly state. TreeMap two methods of sorting:

    1. Natural sort: All keys of treemap must implement the comparable interface, and all keys should be objects of the same class, otherwise the Classcastexcepiton exception will be thrown.
    2. Custom Sort: When you create a treemap, you pass in a comparator object that is responsible for sorting all the keys in the treemap. The comparable interface is not required for the key of the map when custom sorting is Used.

The criteria for determining the equivalent of two keys in TreeMap is also two keys that return true by equals, and the return of 0,treemap by the CompareTo method is considered equal to the two keys.

If you use a custom class as a treemap key, you should re-return the Equals method and the CompareTo method of the class with a consistent result: that is, when two keys return true through the equals method, they should return 0 through the CompareTo method Comparison. If the Equals method is inconsistent with the return result of the CompareTo method, either the TreeMap differs from the map interface (when equals returns true, but the CompareTo comparison does not return 0 o'clock), Either the TreeMap processing performance decreases (when The CompareTo comparison returns 0, when equals does not return true).

TreeMap provides a series of access to the Key-value method in map based on the key sequence:

  1. Map.entry firstentry (): Returns the key-value pair that corresponds to the smallest key in the map, or null if the map is Empty.
  2. Object firstkey (): Returns the minimum key value in the map, or null if the map is Empty.
  3. Map.entry lastentry (): Returns the key-value pair that corresponds to the largest key in the map, or null if the map is empty, or if no such key-value Exist.
  4. Object Lastkey (): Returns the maximum key value in the map, or null if the map is empty, or if no such key exists.
  5. Map.entry higherentry (Object key): returns the key-value pair (the Key-value pair that corresponds to the smallest key greater than the specified Key) in the map that is located after the Key. If the map is empty, null is Returned.
  6. Object Higherkey (): Returns the key value (that is, the minimum key value greater than the specified Key) in the map after Key. If the map is empty, or if no such key is present, null is Returned.
  7. Map.entry lowerentry (Object key): returns the key-value pair (that is, The key-value pair that corresponds to the maximum key of the specified Key) in the map that is located in the previous position of Key. If the map is empty, or if no such key-value is present, null is Returned.
  8. Object Lowerkey (): Returns the key value (that is, The maximum key value less than the specified Key) in the map before the Key. If the map is empty, or if no such key is present, null is Returned.
  9. Navigablemap SubMap (object fromkey, Boolean frominclusive, object tokey, boolean tolnclusive): returns the Map's child map, The range of its key is from Fromkey (whether it includes the second parameter) to Tokey (whether It is included depending on the fourth parameter).
  10. Sortermap subMap (object fromkey, object tokey): Returns the Map's child map whose key range is from Fromkey (including) to Tokey (not included).
  11. SortedMap tailmap (Object Fromkey,boolean inclusive): Returns the Map's child map whose key range is greater than Fromkey (whether It includes all keys depending on the second parameter).
  12. Navigablemap Headmap (Object tokey, boolean lnclusive): returns the Map's child map whose key range is less than Fromkey (whether it includes all keys depending on the second parameter).

Examples of programs:

R class, overriding the equals method, if the Count property equals return True//overrides the CompareTo (Object obj) method, If the Count property equals return 0;class R implements Comparable{int    Count    Public R (int Count) {this.count = count;    The public String toString () {return "R" (count property: "+ count +") ";        } public boolean equals (Object obj) {if (this = = Obj) {return true;            } if (obj! = null && obj.getclass () = = R.class) {r r = (r) obj;            if (r.count = = This.count) {return true;    }} return false;        } public int CompareTo (Object obj) {r r = (r) obj;        If (this.count > R.count) {return 1;        } else if (this.count = = R.count) {return 0;        } else {return-1;        }}}public class Testtreemap{public static void main (string[] Args) {TreeMap tm = new TreeMap (); Tm.put (neW R (3), "lightweight EE enterprise Application practice");        Tm.put (new R ( -5), "Struts2 authoritative guide");        Tm.put (new R (9), "ror Agile Development Best practices");        System.out.println (tm);        Returns the first entry object of the TreeMap System.out.println (tm.firstentry ());        Returns the last key value of the TreeMap System.out.println (tm.lastkey ());        Returns the minimum key value of the TreeMap greater than the new R (2).        System.out.println (tm.higherkey (new R (2)));        Returns the largest key-value pair of the treemap smaller than the new R (2).        System.out.println (tm.lowerentry (new R (2)));    Returns the TreeMap of the TreeMap System.out.println (tm.submap (new R ( -1), new R (4))); }}

Operation Result:

{r (count property: -5) =struts2 authoritative guide, r (count property: 3) = lightweight Java EE enterprise application combat, r (count property: 9) =ror Agile Development Best practices}
R (count property: -5) =struts2 authoritative Guide
R (count property: 9)
R (count property: 3)
R (count property: -5) =struts2 authoritative Guide
{R (count property: 3) = lightweight Java EE enterprise application combat}

Java Collection Framework summary (5) use of The--map interface

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.