java-Base-map Interface

Source: Internet
Author: User
Tags map class modifier set set shuffle

Map interface

The collection under the Map interface and the collection under the collection interface, which store the data in a different form

L Collection A collection in which elements are isolated (understood to be single) and stored as elements in the collection.

A set of maps in which elements are paired (understood as couples). Each element consists of a key and a value, which can be used to find the corresponding value.

the set in L collection is called a single -column collection, andthe collection in map is called a double-row collection.

Note that the collection in map cannot contain duplicate keys, values can be duplicated, and each key can only correspond to one value.

the common collection in map is HashMap collection, Linkedhashmap collection.

Common collections in Map interfaces

Mashmap Collection--------------- hash table structure, does not guarantee the order of element access consistent

Linkedmap Collection------------- hash table structure + linked list structure through the chain list structure can guarantee the access order consistent, through the hash list can guarantee the key is unique, need to rewrite the hashcode () method and the Equals () method

The collection in the map interface has two generic variables (k,v) and, when used, assigns data types to two generics, which can be the same or different.

Common methods in Map interfaces:

Get method : Gets the value that corresponds to the specified key (key)

Remove method : Deletes an element based on the specified key (key), returning the value of the deleted element (value).

Put method : The specified key corresponds to the value and is added to the collection, and the method returns the value corresponding to the key

When using the Put method, if the specified key (key) is not in the collection, there is no value corresponding to the key, returns NULL, and adds the specified key value to the collection;

When using the Put method, if the specified key (key) exists in the collection, the return value is the value corresponding to the key in the collection (the value is the value before the substitution), and the value corresponding to the specified key is replaced with the specified new value.

 Public classMapdemo { Public Static voidMain (string[] args) {//Create a Map objectmap<string, string> map =NewHashmap<string,string>(); //adding elements to the mapMap.put ("Monday", "Monday"); Map.put ("Sunday", "Sunday"); SYSTEM.OUT.PRINTLN (map); //{Sunday =sunday, Monday =monday}//when adding an element to a map, the original value value corresponding to the key is returned, and NULL is returned if the key does not have a corresponding valueSystem.out.println (Map.put ("Monday", "Mon"));//MondaySYSTEM.OUT.PRINTLN (map);//{Sunday =sunday, Monday =mon}//gets the corresponding value according to the specified keyString en = Map.get ("Sunday"); System.out.println (en); //Sunday//Deleting an element according to key will return the value of the key corresponding toString value = Map.Remove ("Sunday"); System.out.println (value); //SundaySYSTEM.OUT.PRINTLN (map);//{Monday =mon}    }}
Map Set Traversal key Find Value method

Key to find the value: that is, by the key in the element, the value corresponding to the key is obtained

Gets all the keys in the map collection because the keys are unique, so returning a set collection stores all the keys

. Iterate through the set of keys to get each key

Gets the value corresponding to the key, depending on the key

 Public classMapdemo { Public Static voidMain (string[] args) {//Create a Map objectmap<string, string> map =NewHashmap<string,string>(); //adding elements to the mapMap.put ("Deng Chao", "Sun Li"); Map.put ("Li Chen", "Fan Bingbing"); Map.put ("Andy Lau", "spokesperson"); //get all keys in a mapSet<string> KeySet =Map.keyset (); //Traverse a set set that holds all keysIterator<string> it =Keyset.iterator ();  while(It.hasnext ()) {//get each keyString key =It.next (); //get the corresponding value by keyString value =Map.get (key); SYSTEM.OUT.PRINTLN (Key+"="+value); }    }}

map set Traversal key value pair mode

Key-value pairs: Gets the keys and values in a key-value pair (Entry) object through each key-value pair (Entry) object in the collection.

entry Key-value pair object

In the map class design, a nested interface is provided: Entry. Entry encapsulates the corresponding relationship of a key-value pair into an object. That is, the key-value pair object, so that when we traverse the map collection, we can get the corresponding key and corresponding value from each key-value pair (Entry) object.

L entry is a static internal nested interface provided in the map interface. static Interface Map.entry (K,V)

GetKey () Method: Gets the key in the entry object

GetValue () Method: Gets the value in the entry object

EntrySet () Method: Used to return all the key-value pairs (Entry) objects in the Map collection, returned as a set collection.


 Public classMapdemo { Public Static voidMain (string[] args) {//Create a Map objectmap<string, string> map =NewHashmap<string,string>(); //adding elements to the mapMap.put ("Deng Chao", "Sun Li"); Map.put ("Li Chen", "Fan Bingbing"); Map.put ("Andy Lau", "spokesperson"); //gets the corresponding relationship of all keys in the map to valueSet<map.entry<string,string>> EntrySet =Map.entryset (); //traversing set CollectionIterator<map.entry<string,string>> it =Entryset.iterator ();  while(It.hasnext ()) {//get each pair of correspondenceMap.entry<string,string> Entry =It.next (); //the corresponding key is obtained through each correspondence relationString key =Entry.getkey (); //the corresponding value is obtained through each correspondence relationString value =Entry.getvalue (); SYSTEM.OUT.PRINTLN (Key+"="+value); }    }}

Note: The map collection cannot be traversed directly using iterators or foreach. But you can use it after you turn it into a set.

HashMap Storing custom type key values

When storing custom objects in HashMap, if the custom object exists as a key, then to ensure that the object is unique, you must override the Hashcode and Equals methods of the object (if you forget, review HashSet storing the custom object).

If you want to ensure that the keys stored in the map are in the same order as they are taken out, you can use the Linkedhashmap collection to store them.

Static Import

In the course of the guide we can import the static part directly, so that the static members of a class can directly use the

Static import Format:

Import static XXX.   YYY; YYY can be used directly after import.

Import StaticJava.util.Map.Entry; Public classHashmaptest { Public Static voidMain (string[] args) {//1, create the HashMap collection object. map<student,string> map =NewHashmap<student,string>(); //Remove the element. Key-value pair mode//set<map.entry<student, string>> entryset = Map.entryset ();Set<entry<student, string>> entryset =Map.entryset (); //for (map.entry<student, string> entry:entryset) {         for(Entry<student, string>Entry:entryset) {Student key=Entry.getkey (); String value=Entry.getvalue (); System.out.println (key.tostring ()+"....."+value); }    }}

variable Parameters

After JDK1.5, if we define a method that needs to accept multiple parameters, and multiple parameter types are consistent, we can simplify it to the following format:

Modifier return value type method name (parameter type ... formal parameter name) {}

In fact, this writing is entirely equivalent to

Modifier return value type method name (parameter type [] formal parameter name) {}

Only in the latter definition, the array must be passed at invocation, and the former can pass the data directly.

jdk1.5 later. Simplified operation has occurred. ... Used on parameters, called variable parameters.

The array is also represented, but when you call this method with a mutable argument, you do not have to create an array

The elements in the array are passed directly as actual parameters, actually compiled into a class file, which encapsulates the elements into an array before being passed. These actions are automatically completed when compiling the. class file.

 Public classParamdemo { Public Static voidMain (string[] args) {int[] arr = {21,89,32}; intsum =Add (arr);        SYSTEM.OUT.PRINTLN (sum); Sum= Add (21,89,32);//variable parameter invocation formSystem.out.println (sum); }    //Writing after JDK1.5     Public Static intAddint... arr) {        intsum = 0;  for(inti = 0; i < arr.length; i++) {sum+=Arr[i]; }        returnsum; }    //Original Wording    /*public static int add (int[] arr) {int sum = 0;        for (int i = 0; i < arr.length; i++) {sum + = Arr[i];    } return sum; }    */}

L The above Add method can only exist in the same class. Because the uncertainty of the call will occur

Note: If this method has multiple parameters when the method is written, the parameter contains variable arguments, and the variable parameter must be written at the end of the parameter list.

Collections Collection Tool Class

Public static <T> void sort (list<t> List) //Collection element sort

Sort before element list collection element [33,11,77,55]

Collections.sort (list);

Post-order element list collection element [11,33,55,77]

Public static void Shuffle (list<?> List) //collection element storage location scrambled

List collection elements [11,33,55,77]

Collections.shuffle (list);

With the shuffle method, the elements in the collection are [77,33,11,55], and each time the method is executed, the position of the elements stored in the collection is randomly disturbed

Collection Nesting

ArrayList Nesting ArrayList

arraylist< arraylist<string> >

collection< arraylist<integer> >

Map Nesting ArrayList

Hashmap<string, arraylist<person>>

arraylist< hashmap<string, string>>

Map Collection Nesting

Hashmap<string, hashmap<string,string>>

Hashmap<string, hashmap<person,string>>

Object-oriented thought of set inheritance system

Interface: used to clarify all the functions in the collection, equivalent to the definition of the set of functional standards;

Abstract class: multiple sets of functions implemented in the same way, extracted to the abstract class implementation, the specific collection is no longer written, inherited use can be;

Concrete classes: Inheriting abstract classes, implementing interfaces, overriding all abstract methods, and achieving a set of specified functions. Each specific collection class, according to its own data storage structure, the interface of the functional methods, the implementation of different ways.

java-Base-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.