java--(eight) Map of Linkedhashmap, TREEMAP, Enummap realization class

Source: Internet
Author: User

------Java Training, Android training, iOS training,. NET training, look forward to communicating with you! -------

1.LINKEDHASHMAP Implementation Class

Linkedhashmap need to maintain a conscious insertion order, so performance is slightly lower than hashmap performance;

Lists to maintain the internal order, so you will have better performance when iterating through all the elements of the map. Here's a demonstration.

The Linkedhashmap function.

1 ImportJava.util.LinkedHashMap;2 3  Public classLinkedhashmaptest {4 5      Public Static voidMain (string[] args) {6 7Linkedhashmap scores =NewLinkedhashmap<>();8Scores.put ("Language", 80);9Scores.put ("Mathematics", 82);TenScores.put ("English", 76); One          for(Object key:scores.keySet ()) { ASYSTEM.OUT.PRINTLN (key + "--->" +Scores.get (key)); -         } -     } the  -}

Operation Result:

Chinese--->80 mathematics --->82 English --->76

2. Use properties to read and write property files

The properties class is a subclass of the Hashtable class, which is particularly handy when working with file properties. The Properties class can

The Map object and the property file are associated so that the key-value pairs in the map object can be written to the property file, or the

Property name = attribute value in the file is loaded into the map object. Because property names and property values in a property file can only be string classes

Type, so the key and value in the properties are string types. This type provides the following three ways to modify the properties

The value of the key in the

1) string GetProperty (String key): Gets the property value corresponding to the property name specified in properties, similar to the map's

The Get (Object key) method.

2) GetProperty (string key, String defaultvalue): This method is basically similar to the previous method. The method is more than one

function, the method specifies a default value if the specified key does not exist in the properties.

3) Object Setproperaty (string key, String value): Sets the property value, similar to the Hashtable put () method.

In addition, it provides two ways to read and write field files.

4) void load (InputStream instream): Loads the Key-value pair from the properties file (represented by the input stream), loads the

To the Key-value to append to the properties.

5) void Store (OutputStream out, String comments): Outputs the Key-value in the properties to the specified

The properties file (in the output stream representation).

The following procedure demonstrates the use of the properties class.

1 ImportJava.io.FileInputStream;2 Importjava.io.FileNotFoundException;3 ImportJava.io.FileOutputStream;4 Importjava.io.IOException;5 Importjava.util.Properties;6 7 8  Public classPropertiestest {9 Ten      Public Static voidMain (string[] args)throwsFileNotFoundException, IOException { One  AProperties props =NewProperties (); -         //adding attributes to Properties -Props.setproperty ("Uername", "Jinan Snow"); theProps.setproperty ("Password", "123456"); -         //save Key-value in properties to the A.ini file -Props.store (NewFileOutputStream ("A.ini"), "Comment Line"); -         //Create a new properties object +Properties PROPS2 =NewProperties (); -         //adding attributes to Properties +Props2.setproperty ("Age", "20"); A         //Append Key-value pairs from the A.ini file to Props2 atProps2.load (NewFileInputStream ("A.ini")); - System.out.println (PROPS2); -     } -  -}

Operation Result:

{age=20, password=123456, uername= and Snow}

The program generates a A.ini file under the current path with the following contents:

23:53:36 CSTpassword=123456uername=\u66a8\u96ea

3.TREEMAP Implementation Class

TreeMap is a red-black tree data structure, each key-value as a node of the red-black tree. TreeMap Storage

Key-value, you need to sort the nodes according to key. TreeMap ensures that all key-value are in an orderly

State. TreeMap also has two kinds of sorting methods. Similar to the criteria for judging the equivalence of elements in the TreeSet, judging by the two keys in TreeMap

The same criteria are: Two keys returned by the CompareTo () method 0,treemap that the two keys are equal. Rewrite

The Equals () method of the class and the CompareTo () method should maintain consistent return results: Two keys are compared by Equals () method

When true, they should return 0 through the CompareTo () method, otherwise the rules for TreeMap and map interfaces will conflict.

The following provides a way for treemap to access the Key-value pair based on the key sequence.

1) map.entry firstentry (): Returns the key-value pair corresponding 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 maximum key value in the map, or null if the map is empty or does not exist for such key-value.

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 (that is, the minimum key value greater than the specified key) in the MAP after key.

If the map is empty, NULL is returned.

6) Object Higherkey (Object key): 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 there is no such key, then NULL is returned.

7) Map.entry Lowerentry (Object key): Returns the key value in the Map that precedes key (that is, the maximum key that is less than the specified key)

The key-value pair). If the map is empty or does not exist such a key-value, then NULL is returned.

8) Object Lowerentry (Object key): 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 does not have such a key-value, it returns null

9) Navigablemap SubMap (Object Fromkey, Boolean frominclusive, Object Tokey, Boolean toinclusive):

Returns the map's child map whose key range is from Fromkey (whether it includes the second parameter) to Tokey (whether it is included depending on the fourth parameter).

Srotedmap SubMap (Object Fromkey, Object Tokey): Returns the map's child map, whose key range is from Fromkey (including)

To Tokey (not included).

One) SortedMap Tailmap (Object fromkey): Returns the map's child map, whose key range is greater than fromkey (including) all keys.

Navigablemap Tailmap (Object fromkey, Boolean inclsive): Returns the map's child map whose key range is greater than fromkey

(whether to include all keys that depend on the second parameter).

SortedMap Headmap (Object tokey): Returns the map's child map whose key range is less than Fromkey (not included) for all keys.

Navigablemap Headmap (Object Tokey, Boolean inclusive): Returns the map's child map whose key range is greater than fromkey

(whether to include all keys that depend on the second parameter).

The following procedure demonstrates the basic usage of treemap. (Natural sort)

1 ImportJava.util.TreeMap;2 3 classRcImplementsComparable {4     intcount;5 6      PublicRc (intcount) {7          This. Count =count;8     }9 Ten @Override One      PublicString toString () { A  -         return"R[count:" + Count + "]"; -     } the  - @Override -      Public Booleanequals (Object obj) { -         if( This==obj) { +             return true; -         } +         if(obj! =NULL&& Obj.getclass () = = Rc.class) { ARc r =(Rc) obj; at             returnR.count = = This. Count; -         } -         return false; -     } -  - @Override in      Public intcompareTo (Object o) { -  toRc r =(Rc) o; +         returnCount > R.count? 1:count < r.count-1? -1:0; -     } the } *  $  Public classTreemaptest {Panax Notoginseng  -      Public Static voidMain (string[] args) { the          +TreeMap TMap =NewTreemap<>(); ATmap.put (NewRc (3), "Dark Horse programmer"); theTmap.put (NewRc ( -5), "CSDN"); +Tmap.put (NewRc (9), "Preach Intelligence podcast"); - System.out.println (TMAP); $         //returns the first entry object of the TreeMap $ System.out.println (Tmap.firstentry ()); -         //returns the last key value of the TreeMap - System.out.println (Tmap.lastkey ()); the         //returns the minimum key value of the TreeMap greater than the new R (2) -System.out.println (Tmap.higherkey (NewRc (2)));Wuyi         //returns the largest key-value of the treemap smaller than the new R (2) theSystem.out.println (Tmap.higherentry (NewRc (2))); -         //returns the child treemap of the TreeMap WuSystem.out.println (Tmap.submap (NewRc (-1),NewRc (5))); -     } About  $}

Operation Result:

{r[count:-5]=csdn, r[count:3]= Dark Horse programmer, r[count:9]= podcast}r[count:-5]=csdnr[count:9]r[count: 9]r[count:9]= Podcast {r[count:3]= Dark Horse Programmer}

4.ENUMMAP Implementation Class

Enummap is a map implementation that is used with enumerations, and all keys in ENUMMAP must be enumerated values of a single enumeration class.

The enummap is stored internally as an array, so this is a very compact and efficient form of implementation. Enummap according to the natural sort of key (

That is, enumeration values are defined in the enumeration class order) to maintain the order of the key-value pairs.

The following procedure demonstrates the use of enummap.

1 ImportJava.util.EnumMap;2 3 enumSeason {4 SPRING, SUMMER, FALL, Winrer5 }6 7  Public classEnummaptest {8 9      Public Static voidMain (string[] args) {Ten  One         /*creates an Enummap object that all keys of the ENUMMAP must be enumerated values of the season enumeration class*/ AEnummap Enummap =NewEnummap<> (Season.class); -Enummap.put (Season.summer, "summer scorching"); -Enummap.put (season.spring, "Spring Blossoms"); the System.out.println (enummap); -     } -  -}

Operation Result:

{spring= Spring, summer= summer heat}

The above program creates the Enummap object that specifies that its key can only be an enumeration value of the season enumeration class. If the

After adding two key-value pairs in Enummap, these two key-value pairs will have a natural value of season enumeration

Sequential sorting.

java--(eight) Map of Linkedhashmap, TREEMAP, Enummap realization class

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.