"Javase" Day05_map interface _hashmap_hashcode

Source: Internet
Author: User
Tags set set

"Javase" Day05_map interface _hashmap_hashcode


1.Map Interface

1) Java.util.Map

The map looks like a two-column table with multiple rows. Each record is divided into two parts: Key,value.

Where key is not allowed to be duplicated in a map (equals comparison)

2) Common Implementation class: JAVA.UTIL.HASHMAP (hash Algorithm implementation)

JAVA.UTIL.TREEMAP (binary tree implementation)

3) V put (K k,v v)

The given key and value are stored in the map. Because key in map does not allow duplication, there are two scenarios:

* 1: The key stored in the map does not already exist, then the key-value directly into the map, the return value is null.

* 2: The key stored in the map already exists, then the corresponding value will replace the value of the original key corresponding to the value, and will be replaced by values returned.

4) V get (k k)

Gets the corresponding value based on the given key value. If the current map does not contain the given key, the return value is null.

5) V remove (k k)

This pair of content corresponding to the given key is removed from the map and the corresponding value is returned.

6) Boolean ContainsKey (k K)

See if the current map contains a given key. The included judgment is based on the result of the equals comparison of key

Code Demo:

<span style= "FONT-SIZE:18PX;" >package day05;import java.util.hashmap;import java.util.map;/** * JAVA.UTIL.MAP * Map looks like a multi-row, two-column table * Each record is divided into two parts: key , value * Where key is not allowed to be duplicated in a map. (Equals comparison) * * Common Implementation class: JAVA.UTIL.HASHMAP (hash Algorithm implementation) * JAVA.UTIL.TREEMAP (binary tree Implementation) */public class MapDemo1 {public static V OID Main (string[] args) {/* * Save transcript language -90 */map<string,integer>map = new hashmap<string,integer> ();/* * V put (K k,v V) * Deposit the given key and value into the map. * Because the key in the map is not allowed to be duplicated, there are two cases: * 1: The key stored in the map does not exist, then direct the key-value to map, the return value is NULL * 2: The key stored in the map already exists, then the corresponding * Valu E replaces the value of the original key and returns the value that is replaced by *. * */map.put ("language"), Map.put ("mathematics"), Map.put ("English", "Map.put"), Map.put ("Physics", "98");/* * The Order of deposit is inconsistent with the internal order */ SYSTEM.OUT.PRINTLN (map), Integer a =map.put ("Language 1",//int a =map.put ("Language 1", 100); Null pointer exception, written as Integer can avoid System.out.println (a); SYSTEM.OUT.PRINTLN (map),/* * V get (k k) * Gets the corresponding value based on the given key value * If the current map does not contain the given key, the return value is null */integer num = map.get ("chemical"); S Ystem.out.println (NUM) */* * V remove (k k) * Remove the pair of content corresponding to the given key from the map and return the corresponding value. */num = Map.Remove ("chemistry"); SYSTEM.OUT.PRINTLN (num); SYSTEM.OUT.PRINTLN (map),/* * Boolean containskey (k k) * To see if the current map contains a given key * contains the judgment based on the result of the equals comparison of key */boolean contains = Map.containskey ("language"); System.out.println (contains);}} </span>

7) Map three ways to traverse:

<span style= "FONT-SIZE:18PX;" >package day05;import java.util.collection;import Java.util.linkedhashmap;import java.util.Map;import Java.util.set;import java.util.map.entry;/** * Traverse map * There are three ways to traverse a map: * 1: Traverse all key * 2: Iterate through each set of key-value pairs * 3: Traverse all values (relatively infrequently) * */pub Lic class MapDemo2 {public static void main (string[] args) {/* * LINKEDHASHMAP * Internal uses a LinkedList maintenance order, which can be done while traversing the order of the put Induced by. If order is not allowed, the class is usually not used. */map<string,integer> Map = new linkedhashmap<string,integer> (), Map.put ("language", "Chinese"), Map.put ("Mathematics", 98); Map.put ("English", "Map.put"), Map.put ("Physics", "the", "90"); SYSTEM.OUT.PRINTLN (map);/* * traverse all keys: * set<k> keySet () * This method will return all keys to a set set, so traversing the collection is the equivalent of traversing through all the keys. */set<string> KeySet = Map.keyset (); for (String Key:keyset) {System.out.println (key);} /* * Iterate through each set of key-value pairs * set<entry> entryset () * Returns each set of key-value pairs (Entry instances) into a set set. * * Entry is the inner class of map, each instance represents a set of key-value pairs * which contains two attributes, Key,value. */set<entry<string,integer>> EntrySet = Map.entryset (); for (entry<string,integer> E: entryset) {String key = E.getkey (); Integer num = E.getvalue (); System.out.println (key+ "--" +num);} /* * collection<v> VALUES () * Returns all value values in the current map after they are saved to a collection. */collection<integer> values = Map.values (); for (Integer i:values) {System.out.println (i);}}} </span>

2.HashMap

HashMap is a common subclass implementation of map. In fact, the hash algorithm is used to achieve.

HashMap internally maintains a hash array (that is, an array of stored elements), which we call a hash bucket, and when we deposit a set of key-value pairs into the HashMap, HashMap first gets the return value of the Hashcode () method of the Key object. The value is then used to make a hash algorithm, which is a number that is the set of key-value pairs to be stored in the hash array in the subscript position.

When you know the subscript position, HashMap also checks to see if the current location of the hash array contains the element. (note here that each element in the hash array is not a direct store of a key-value pair, but rather a linked list in which each node in the list is actually holding the set of key-value pairs.) ) checks if the element is included, depending on whether the key currently being stored in the current hash array corresponds to the link in the list, if it does not contain the set of key-value pairs in the linked list, or replace value.

Then, when the element is fetched, HashMap also hashes the algorithm based on the hashcode value of the key, finds its position in the hash array, and then iterates through the linked list of the position, and returns the value corresponding to the key.

See here may have a question, the list should only be stored in one element, then HashMap is how to put Key-value into a linked list of a node? In fact, HashMap encapsulates each set of key-value pairs as an instance of entry and then stores the instance in a linked list.


3.hashCode

When we use an instance of a custom type as the value of key in HashMap, the result of this class equals and hashcode directly affects the efficiency of the HASHMAP query.

* To avoid the creation of something:

Hashcode values are the same, but equals is not true!! This can seriously affect hashmap efficiency.

* There is a requirement for rewriting these two methods in the JAVA API documentation:

When we rewrite the Equals method of a class, we should go along with overriding the Hashcode method.

* You should also meet:
The value returned by hashcode should be equal when the equals of two objects is compared to true. In turn not mandatory, but preferably also different, otherwise affect hashmap performance.

The return value of the Hashcode method should be a stable value, meaning that the return value of the Hashcode method should be the same when multiple calls are made to determine that the attribute of the comparison result of the Equals method is not changed.

Code Demo:

<span style= "FONT-SIZE:18PX;" >package day05;/** * This class is used to practice overriding the Equals and hashcode considerations: * When we use an instance of a custom type as the value of key in HashMap, * The results of the equals and hashcode of this class directly affect the efficiency of hashmap query. * To avoid the creation of one thing: * Hashcode values are the same, but equals is not true!! This can seriously affect * hashmap efficiency. * There is a requirement in the JAVA API documentation for rewriting these two methods: * When we rewrite the Equals method of a class, we should rewrite the Hashcode method together. * should also satisfy: * When the two objects equals True, the value returned by hashcode should be equal. * In turn not mandatory, but preferably also different, otherwise affect hashmap performance. The return value of the *hashcode method should be a stable value, meaning that the return value should be the same when the property that determines the comparison result of the equals * method is not changed, and the Hashcode method is called multiple times. * */public class Cell {private int row;private int col;public cell (int row, int col) {super (); this.row = Row;this.col = Co l;} @Overridepublic int hashcode () {final int prime = 31;int result = 1;result = Prime * result + Col;result = Prime * result + Row;return result;} @Overridepublic boolean equals (Object obj) {if (this = = obj) return true;if (obj = = null) return False;if (GetClass ()! = obj . GetClass ()) return false;final Cell other = (Cell) obj;if (col! = Other.col) return false;if (Row! = Other.row) return False ; return true;}} </span> 

4.Map Small Case List

<span style= "FONT-SIZE:18PX;" >package day05;import java.util.hashmap;import java.util.iterator;import java.util.map;import java.util.Set; Import java.util.map.entry;/** * Existing string "Good good study, day-up.", which counts the number of occurrences of each character. * */public class Mapdemo {public static void main (string[] args) {String str = ' good good study, day ' up. '; Summary (str);} public static map<character,integer> Summary (String str) {//"good good study. map<character,integer> map = new hashmap<character,integer> ();//remove spaces and punctuation in a string//regex = "[^a-za-z]+" str = Str.replaceall ("[^a-za-z]+", "" "); System.out.println (str); for (int i=0;i<str.length (); i++) {char c = str.charat (i); if (Map.containskey (c)) {Map.put (c , Map.get (c) +1);} Else{map.put (c,1);}} The new loop traverses Set<entry<character,integer>>entryset = Map.entryset (); for (entry<character,integer> e: EntrySet) {System.out.println (E.getkey () + "--" +e.getvalue ());} Iterator iterator traversal key-valueiterator<entry<character,integer>> it2 = enTryset.iterator (); while (It2.hasnext ()) {//it.next () can only occur once per loop, otherwise it may throw an exception entry<character,integer> E = It2.next (); Char key = E.getkey (); Integer value = E.getvalue (); SYSTEM.OUT.PRINTLN (Key + "--" +value);} The iterator traverses keyset<character> KeySet = Map.keyset ();iterator<character> it = Keyset.iterator (); while ( It.hasnext ()) {System.out.print (It.next () + "");} System.out.println (); return null;}} </span>






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

"Javase" Day05_map interface _hashmap_hashcode

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.