Map is used to save data with ing relationships (key-vlaue ). Duplicate Map keys are not allowed. That is, if two keys of the same Map object are compared using the equals method, false is always returned.
Map contains a keySet () method, which is used to return a Set composed of Map and key.
The Map Set and the Set element are stored in a similar way. For example, the Set Interface contains implementation classes and subinterfaces, such as HashSet, javashashset, SortedSet (Interface), TreeSet, and EnumSet, in the Map interface, there are implementation classes and subinterfaces such as HashMap, LinkedHashMap, SortedMap, TreeMap, and EnumMap.
The value of Map is very similar to List: Elements and elements can be repeated. Each element can be searched by index (key.
Map is sometimes called a dictionary or an associated array.
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 specified key is included in the Map. If the key is included, true is returned.
- Boolean containsValue (Object value): queries whether Map contains one or more values. If it contains values, returns true.
- Set entrySet (): returns a Set composed of all key-value pairs in the Map. Each Set element is a Map. Entry (Entry is an internal class of Map) object.
- Object get (Obejct key): returns the value corresponding to the specified key. If the Map does not contain the key, null is returned.
- Boolean isEmpty (): checks whether the Map is null (that is, it does not contain any key-value pairs). If it is null, true is returned.
- Set keySet (): returns the set Set composed of all keys in the Map.
- Object put (Object key, Object value): Add a key-value pair. If the current Map already has a key-value Pair equal to the key, the new key-value Pair overwrites the original key-value pair.
- Object remove (Object key): deletes the key-value pair corresponding to the specified key, and returns the value associated with the deleted key. If the key does not exist, null is returned.
- Int size (): returns the number of key-value pairs in the Map.
- Collection values (): returns the Collection composed of all values in the Map.
The Map interface provides a large number of implementation classes, such as HashMap and Hashtable, as well as the HashMap subclass LinkedHashMap, as well as the SortedMap sub-interface and the implementation class TreeMap of this interface. The following is a detailed introduction.
Map contains an internal class: Entry. This class encapsulates a key-value pair. The Entry contains three methods:
- Object getkey (): return the key value contained in the Entry.
- Object getValue (): returns the value contained in the Entry.
- Object setValue (): set the value contained in the Entry and return the new value.
Map can be understood as a special Set, but the Set element in the Set is an Entry object rather than a common object.
1. Implementation class of HashMap and Hashtable
Both HashMap and Hashtable are implementation classes of the Map interface. Hashtable is an ancient Map implementation class that has been available since JDK1.0. It contains two cumbersome Methods: elements () (similar to the values () method defined by the Map interface) and keys () (similar to the keySet () method defined by the Map interface), these two methods are rarely used.
Two differences:
- Hashtable is a thread-safe Map implementation, but HashMap is a thread-safe implementation, so HashMap has higher performance than Hashtable. However, if multiple threads access the same Map object, it is better to use Hashtable to implement the class.
- Hashtable does not allow null as the key and value. If it is null, NullPointerException is thrown. However, HashMap can use null as the key or value.
Because HashMap can be unique, only one key-value Pair in HashMap can be null, but there can be countless key-value pairs whose values are null.
HashMap overwrites the toString () method and always returns a string in the following format: {key1 = value1, key2 = value2 ..}
HashMap and Hashtable determine that two keys are equal: two keys use the equasl method to compare and return true, and the hashCode values of the two keys are equal.
LinkedHashMap class
HashMap has a subclass: LinkedHashMap, which is also a two-way linked list to maintain the order of key-value pairs. This Linked List defines the iteration sequence, the iteration sequence is consistent with the insertion sequence of key-value pairs.
LinkedHashMap can avoid sorting key-value pairs in HashMap and Hashtable (as long as the key-value pair is inserted in sequence ). At the same time, you can avoid the increased cost of using TreeMap.
LinkedHashMap needs to maintain the insertion sequence of elements, so its performance is slightly lower than that of HashMap. However, it performs well when iteratively accessing all elements in Map, because it maintains the internal order by using a linked list.
Properties class
The Properties class is a subclass of the Hashtable class and is used to process property files (such as INI files on Windows operating platforms ). The Properties class can associate the Map object with the attribute file, so that the key-value pair in the Map object can be written to the attribute file, you can also load the property name = property value in the property file to the Map object. Because the attribute names and attribute values in the property file can only be strings, the keys and values in Properties are strings, this class provides the following three methods to modify the key and value values in Properties.
- String getProperty (String key): gets the attribute value corresponding to the specified property name in Properties, similar to the get (Object key) method of Map.
- String getProperty (String key, String defaultValue): This method is similar to the previous method. This method has one more function. If the specified key does not exist in Properties, this method returns the default value.
- Object geProperty (String key, String value): Set the attribute value, similar to the put Method of Hashtable.
Two methods are provided to read and write attribute files:
- Void load (InputStream inStream): loads the attribute name = attribute value from the attribute file (expressed as an input stream) and appends the attribute name = attribute value pair to Properties (because Properties is Hashtable) it does not guarantee the order between key-value pairs ).
- Void Store (OutputStream out, String comment): writes the key-valu pair in Properties to the specified attribute file (expressed as an output stream ).
Example program:
Public class TestProperties {public static void main (String [] args) throws Exception {Properties props = new Properties (); // Add the property props to Properties. setProperty ("username", "yeeku"); props. setProperty ("password", "123456"); // save Properties to. props. store (new FileOutputStream (". ini ")," comment line "); // create a Properties object Properties props2 = new Properties (); // Add the property props2.setProperty (" gender ", "male"); // set. the property name-property value in the INI file is appended to props2.load (new FileInputStream (". ini "); System. out. println (props2 );}}
Running result:
{Password = 123456, gender = male, username = yeeku}
2. SortedMap interface and TreeMap implementation class
The Map interface derives a SortedMap sub-interface, and the TreeMap is its implementation class. Similar to TreeSet sorting, TreeMap sorts all keys in TreeMap Based on the red/black tree to ensure that all key-value pairs in TreeMap are in an ordered state. TreeMap sorting methods:
- Natural sorting: All keys of TreeMap must implement the Comparable interface, and all keys should be objects of the same class. Otherwise, a ClassCastExcepiton exception will be thrown.
- Custom sorting: When a TreeMap is created, a Comparator object is input, which sorts all keys in the TreeMap. The Comparable interface is implemented using keys that do not require Map during custom sorting.
In TreeMap, the criteria for determining that two keys are equal is that two keys Return true through equals comparison, and 0 is returned through compareTo method. TreeMap considers these two keys to be equal.
If a custom class is used as the key of TreeMap, The equals method and compareTo method of the class should have the same returned result: When two keys are compared to return true through the equals method, the compareTo method returns 0. If the returned results of the equals and compareTo methods are inconsistent, or the rule of the TreeMap and Map interfaces is different (when equals returns true, but CompareTo does not return 0 ), either the TreeMap processing performance is reduced (when compareTo returns 0, when equals does not return true ).
TreeMap provides a series of key-value pairs for access to Map in the key order:
- Map. Entry firstEntry (): returns the key-value pair corresponding to the smallest key in the Map. If the Map is empty, null is returned.
- Object firstKey (): returns the minimum key value in the Map. If the Map is empty, null is returned.
- Map. Entry lastEntry (): returns the key-value pair corresponding to the maximum key in the Map. If the Map is empty or such key-value does not exist, null is returned.
- Object lastKey (): returns the maximum key value in the Map. If the Map is empty or does not exist, null is returned.
- Map. Entry higherEntry (Object key): returns the key-value Pair located after the key in the Map (that is, the key-value pair corresponding to the minimum key greater than the specified key ). If the Map is empty, null is returned.
- Object higherKey (): returns the key value (greater than the minimum key value of the specified key) next to the key in the Map ). If the Map is empty or such a key does not exist, null is returned.
- Map. Entry lowerEntry (Object key): return the key-value Pair located before the key in the Map (that is, the key-value pair corresponding to the maximum key of the specified key ). If the Map is null, or such key-value does not exist, null is returned.
- Object lowerKey (): return the key value (smaller than the maximum key value of the specified key) in the Map before the key ). If the Map is empty or such a key does not exist, null is returned.
- NavigableMap subMap (Object fromKey, boolean fromInclusive, Object tokey, boolean tolnclusive): returns the child Map of the Map, whose key range is from fromKey (whether it includes depends on the second parameter) to tokey (whether to include depends on the fourth parameter ).
- SorterMap subMap (Object fromKey, Object toKey): returns the child Map of the Map. Its key ranges from fromKey (included) to toKey (not included ).
- SortedMap tailMap (Object fromKey, boolean random SIVE): returns the child Map of the Map. Its key range is greater than that of fromkey (whether to include all keys dependent on the second parameter.
- NavigableMap headMap (Object toKey, boolean lnclusive): returns the child Map of the Map. Its key range is smaller than that of fromKey (whether to include all keys dependent on the second parameter.
Program example:
// R class. The equals method is overwritten. If the count attribute is equal, true is returned. // The compareTo (Object obj) method is overwritten. If the count attribute is equal, 0 is returned; class R implements Comparable {int count; public R (int count) {this. count = count;} public String toString () {return "R (count attribute:" + 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 J2EE Enterprise Application Practice "); Tm. put (new R (-5), "Struts2 authoritative guide"); tm. put (new R (9), "ROR best practices for agile development"); System. out. println (tm); // returns the first Entry object System of the TreeMap. 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 value of new R (2. System. out. println (tm. higherKey (new R (2); // returns the largest key-value pair of the TreeMap that is smaller than new R (2. System. out. println (tm. lowerEntry (new R (2); // returns the child TreeMap System of the TreeMap. out. println (tm. subMap (new R (-1), new R (4 )));}}
Running result:
{R (count attribute:-5) = Struts2 authoritative guide, R (count attribute: 3) = Lightweight J2EE Enterprise Application Practice, R (count attribute: 9) = ROR best practices for agile development}
R (count attribute:-5) = Struts2 authoritative guide
R (count attribute: 9)
R (count attribute: 3)
R (count attribute:-5) = Struts2 authoritative guide
{R (count attribute: 3) = Lightweight J2EE Enterprise Application Practice}