I genius official Free Tutorial 33: Map Collection of the Java Collection framework

Source: Internet
Author: User

Map Interfacethe Map collection stores data in a key-value pair (Key-value) where the key cannot be duplicated and the value can be duplicated.
Common classes are HashMap, TreeMap and properties
HashMap classIf, now I have a collection that stores a batch of WiFi names and passwords, now requires a quick name to find the password. Such a requirement is very difficult to implement with the list collection, and Java provides us with another form of collection that can solve this problem well. is the map collection.
Example: Package Map.hashmap;import java.util.hashmap;import java.util.map;/** * Demo HashSet * @author Genius Federation-Yukun */public class Ha Shmapdemo {public static void main (string[] args) {//Create collection Object map map = new HashMap (); */* NOTE: The map collection adds elements by put, not add * previous parameter generation Table key (key), the latter parameter represents value (value) */map.put ("WifiName1", "Password1");/* * When a key is repeated, the following value overrides the previous value * and value repeats without affecting */map.put (" WifiName2 "," Password2 "), Map.put (" WifiName2 "," Password3 "), Map.put (" WifiName3 "," Password3 ");//Gets the length of the set, joins 4 times, Length 3int size = Map.size (); SYSTEM.OUT.PRINTLN (size);//Get Key "WifiName2" for valuestring Wifi2 = (String) map.get ("wifiName2"); System.out.println (WIFI2);//two ways to convert to string can be string wifi3 = Map.get ("WifiName3"). ToString (); System.out.println (WIFI3);}} Running Result: 3password3password3

Note: The set set will store the added elements on the key of the map collection, and if duplicates do not overwrite, keep the previous one, but when the elements in the map collection appear with the same key, key does not overwrite, But value is overwritten by the value added later.

When we talk about adding elements to the Set collection, we create a node that maintains the currently joined element in the node's key. There is also a Value property in the node, which also holds an object, except that the Value property is not used in set. The map collection needs to store two values, key and value, where the first parameter passed in when we call the put method is stored on the node object's property key, and the second parameter passed in is stored on the Node object's property value.
from this point, when using key to get the corresponding value in the Map collection, first by finding the node object in the hash table where the key is located, and then returning the value of values in the Node object, then we get the value of key.

Map Collection A demonstration of some common methods
Example: Package Map.hashmap;import java.util.collection;import java.util.hashmap;import java.util.set;/** * Demonstrates some common methods in the HashMap class * @author Genius Federation-Yukun */public class Hashmapmethoddemo {public static void main (string[] args) {//Create two Class C Lass1 and Class2hashmap class1 = new HashMap (); HashMap Class2 = new HashMap (); * * Add three students to each of the two classes and score * 1 class has a classmate called "Harry", the result is 50 points * 2 class also has a "Harry" classmate, the score is 90 points */class1.put ("Zhang San", "80 Class1.put ("John Doe", "60 Points"), Class1.put ("Harry", "50 points"), Class2.put ("Zhao Si", "80 points"), Class2.put ("Chen VI", "0"); Class2.put ("Harry" , "90 points");//Judge 1 class there is no Name "Harry" Classmate Boolean containskey = Class1.containskey ("Harry"); System.out.println ("There is no key in the set Class1 is Harry:" + ContainsKey); System.out.println ("-------------------------------------");//Judging whether Class 1 has scored 90 points of the classmate Boolean containsvalue = Class1.containsvalue ("90 points"); System.out.println ("The set Class1 has no value in it is 90 points:" + containsvalue); System.out.println ("-------------------------------------");//merge 2 classmates into a class class1.putall (CLASS2);// Get class number (set length) int size = Class1.size (); SYSTEM.OUT.PRINTLN ("Total number of combined classes:" + size); SYstem.out.println ("-------------------------------------");//Get the name of all students in Class 1 set nameset = Class1.keyset ();// Enhanced for loop output all names for (Object o:nameset) {System.out.print (O + "");} System.out.println (); System.out.println ("-------------------------------------");//Get the results of all students in Class 1 collection scores = Class1.values ();// Enhanced for loop output all scores for (Object O:scores) {System.out.print (O + "");} System.out.println (); System.out.println ("-------------------------------------");//Get the names and scores of all students in Class 1 set nameandscoreset = Class1.entryset ();//enhanced for loop output all scores for (Object O:nameandscoreset) {System.out.print (O + "");} System.out.println (); System.out.println ("-------------------------------------");//Get Harry's score Object wangwuscore = Class1.get ("Harry"); System.out.println ("post-merger Harry Score:" + Wangwuscore); System.out.println ("-------------------------------------");//delete the key "Harry" Valueclass1.remove ("Harry");//delete "Harry" After System.out.println ("Harry's score:" + Class1.get ("Harry")); System.out.println ("Does not contain a key called" Harry ":" + Class1.containskey ("Harry")); System.out.println ("Does it contain"90 points" of value: "+ Class1.containsvalue (" 90 points ")); System.out.println ("-------------------------------------");//Replace Chen Liu's class1.replace ("Chen Liu", "59 points"); SYSTEM.OUT.PRINTLN ("Replacement of Chen Liu's results:" + class1.get ("Chen Liu")); System.out.println ("-------------------------------------");//empties the set Class1.clear ();//Determines whether the collection is empty System.out.println ( "Clears the collection after the Clear method is empty:" + class1.isempty ());}}

Summarize:map is stored in the structure of key-value pairs;
When key is duplicated, the newly added key will not overwrite the original key, but the newly added value will overwrite the value of the original key.
Both key and value can use NULL

Special note: The set set is actually storing the element on the map key. When you create a HashSet object A, a HashMap object map is created at the bottom, and Map.put ("abc", obj) is called when you want to add elements to set set a (A.add ("abc")).
Therefore, the implementation of the set is the way the key is implemented in map (array + single-chain table), because the element storage array subscript is obtained by a specific hash algorithm, so also known as hash storage
The following is the source//Creation HashSet object in HashSet is to create a HashMap object in the underlying public HashSet () {map = new hashmap<> ();} When adding an element to the set collection, the underlying is adding the added element to the key on the map collection, public boolean add (e e) {return Map.put (E, PRESENT) ==null;}

TreeMap classas the name indicates, its key is the same as TreeSet, and the other properties are the same as HashMap. So this is no longer a detailed story.
Example: Package Map.treemap;import java.util.set;import java.util.treemap;/** * Demo TreeSet Collection * @author Genius Federation-Yukun */public class Treemapdemo {public static void main (string[] args) {//Create three branch objects Branch B1 = new Branch (10); Branch b2 = new Branch (5); Branch B3 = new Branch (8);//Create TreeMap object TreeMap TM = new TreeMap (); Tm.put (B1, "branches"); Tm.put (B2, "Branch 5"); Tm.put (B3, "Branch 8"); Gets the set of all keys contained in treemap set ts = Tm.keyset ();//Loop Output keyfor (Object o:ts) {Branch b = (Branch) o;//output ring System.out.print (" Rings: "+ b.getannualring ());//According to the ordered key, get the ordered valueSystem.out.println (" corresponding value: "+ tm.get (b));}} /** * Branch Class Branch * The element type that joins the TreeSet collection must implement the comparable interface * Otherwise the program will run with an exception * @author Genius Federation-Yukun */class Branch implements Comparab le{//rings: The basis for ordering the private int annualring;//with the parameter construction method public Branch (int annualring) {this.annualring = annualring;} Overriding the method in the interface @overridepublic int CompareTo (object o) {//coercion type conversion Branch B = (Branch) o;/* * Use rings as the basis for sorting comparisons * Current object ring minus parameter incoming Branch pair The age of the elephant * results equal to 0 means: Two branches of the tree are equal, the order is not divided into two orders * The result is greater than 0 means: The current object has a large annual ring, the result is less than 0 means: The parameter object of the ring large, in the back*/int result = This.annualring-b.annualring;return result;} Get ring public int getannualring () {return annualring;}} Operation result: 5 corresponding value: Branch 5 wheel: 8 corresponding value: Branch 8 year round: 10 corresponding value: Branch 10

Properties Classget a key-value pair from a file
File content Format
Key = value
Example: FileName: Properties.txt file contents: Username = AdminPassword = 123456 file Address: src/map/properties/ Properties.txt where the file address is an instance starting from the project root: Package Map.properties;import Java.io.fileinputstream;import java.util.properties;/** * Demonstrates some common methods in the Properties class * @author Genius Federation-Yukun */public class Propertiesdemo {public static void Mai N (string[] args) {//Create properties Object Properties P = new properties ();/* * The following code temporarily knows what the function is, and will explain later * The function of the Try-catch statement is to catch the exception * Lo The purpose of the ad method is to load the file * where the parameter is the file's address */try {p.load (New FileInputStream ("Src/map/properties/properties.txt"));} catch (Exception e) {System.out.println ("Loading Error");} Gets the value of username in the file string username = P.getproperty ("username"); System.out.println ("User name:" + username);//Gets the value of password in the file string password = p.getproperty ("password"); System.out.println ("Password:" + password);}} Run Result: User name: admin password: 123456


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

I genius official Free Tutorial 33: Map Collection of the Java Collection framework

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.