Java hash and hash code discussion, simple HASHMAP implementation hash map run a variety of operation display columns

Source: Internet
Author: User
Tags lenovo

Java hash and hash code discussion, simple HASHMAP implementation hash map run a variety of operation display columns

Package org.rui.collection2.maps;/** * Hash and hash code * Link the soil-extraction object to the predicted object, * @author Lenovo * *///Groundhog public class Groundhog {protect Ed int number;public Groundhog (int n) {number=n;} @Overridepublic String toString () {return "Groundhog #" + Number;}}

Package Org.rui.collection2.maps;import java.util.random;//Pre-Test public class Prediction {private static Random rand=new Random (;p rivate boolean shadow=rand.nextdouble () >0.5; @Overridepublic String toString () {if (shadow) return " Six weeks after Winter ";//six weeks winter six more weeks of Winterelsereturn" early spring ";//early spring early spring!}}

Package Org.rui.collection2.maps;import Java.lang.reflect.constructor;import Java.lang.reflect.invocationtargetexception;import Java.util.hashmap;import java.util.map;/** * Hash and hash code * The object of soil extraction was associated with the predicted object. * Each groundhog is given a number of identifiers. So I can find prediction in Hasmmap: * Give me and groundhog #3相关的prediction * Prediction class includes a Boolean and ToString * Boolean value initialized with random , and the ToString method interprets the result.

* The Detecspring method uses a reflection mechanism to instantiate a class with the Groundhog class or whatever it derives from groundhog. * * @author Lenovo * */public class Springdetector {//Discover public static <t extends groundhog> void detectspring (class <T> type throws exception{constructor<t> Ghog=type.getconstructor (Int.class); Map<groundhog, prediction> map=new Hashmap<groundhog, prediction> ();//Initialize mapfor (int i=0;i<10;i++) { Map.put (Ghog.newinstance (i), new Prediction ()); System.out.println ("map:=" +map);//Generate a number=3 taxi mouse groundhog Gh=ghog.newinstance (3);//Find the pre-measured System.out.println (" Looking up prediction for: "+gh);//Find if (Map.containskey (GH)) System.out.println (Map.get (GH)) in the map in the initialization; ELSESYSTEM.OUT.PRINTLN ("Key not Found" +gh);//looks very easy, but he does not work, unable to find the need to implement Hacode and equals next chapter commentary}public static void Main ( String[] args) throws Exception {detectspring (Groundhog.class);}} /**output:map:={groundhog #5 = early spring, groundhog #7 = early spring, groundhog #8 = Six weeks after winter, groundhog #0 = Six weeks after winter, groundhog #9 = Six weeks after winter, Groundhog #2 = early spring, groundhog #1 = Six weeks after winter, groundhog #4 = Six weeks after winter,Groundhog #3 = early spring, groundhog #6 = early spring}looking up prediction For:groundhog #3key not found groundhog #3 */


Package org.rui.collection2.maps;/** * Assuming that you want to use your own class as HashMap, you must overload hashcode and Equlas * At the same time * @author Lenovo * */// Groundhog 2public class Groundhog2 extends Groundhog{//public int number;public Groundhog2 (int n) {super (n);} @Overridepublic int hashcode () {return number;} @Overridepublic boolean equals (Object obj) {return obj instanceof Groundhog2 &&  (number== ((Groundhog2) obj) . number);}}

Package org.rui.collection2.maps;/** * Groundhog2.hashcode returns the identification number (number) of the groundhog as a hash code.

* In this example, the program ape is responsible for ensuring that different groundhog have different numbers. Hashcode does not have to always return a unique identifier * But equals must strictly infer whether the object is the same * @author Lenovo * */public class SpringDetector2 {public static void main (string[] args) throws Exception {springdetector.detectspring (Groundhog2.class);}} /**map:={groundhog #0 = Six weeks after the winter, groundhog #1 = Six weeks after the winter, groundhog #2 = early spring, groundhog #3 = early spring, groundhog #4 = Six weeks later is winter, groundhog #5 = early spring , Groundhog #6 = early spring, groundhog #7 = early spring, groundhog #8 = Six weeks later is winter, groundhog #9 = Six weeks later is winter}looking up prediction For:groundhog #3早春 */


Package Org.rui.collection2.maps;import java.util.*;/** * Understanding Hashcode * The purpose of hashing is to use an object to find an object.  * Just use treemap or your self-implemented map to achieve the following demo sample with * Pair ArrayList implement a map * * @author Lenovo * */public class slowmap<k, v>  Extends Abstractmap<k, v> {private list<k> keys = new arraylist<k> ();p rivate list<v> values = new Arraylist<v> ();p ublic v put (K key, V value) {V OldValue = Get (key), if (!keys.contains (key)) {Keys.add (key); VALUES.A DD (value);//Add new} else//it will be used to find a numeric index that represents its position in the keys list and this number is used as an index to produce the value associated with the values list Values.set (Keys.indexof (key), value); return oldValue;} Public V get (Object key) {if (!keys.contains (key)) return Null;return Values.get (Keys.indexof (key));} Public set<map.entry<k, V>> EntrySet () {set<map.entry<k, v>> Set = new hashset<map.entry< K, v>> ();iterator<k> ki = keys.iterator ();iterator<v> VI = Values.iterator (); while (Ki.hasnext ()) { Set.add (New mapentry<k, v> (Ki.next (), Vi.next ()));} RetUrn set;} public static void Main (string[] args) {//Slow slowmap<string, string> map = new slowmap<string, string> (); map.p UT ("Cameroon", "Yaounde"), Map.put ("A", "AA"), Map.put ("B", "BB"), Map.put ("C", "CC"); SYSTEM.OUT.PRINTLN (map); System.out.println (Map.get ("A")); System.out.println (Map.entryset ());}} /**output:{cameroon=yaounde, C=CC, B=BB, A=aa}aa[cameroon=yaounde, C=CC, B=BB, A=AA] * *

Package Org.rui.collection2.maps;import java.util.map;/** * If you want to create your own MAP type, you must define the implementation of Map.entry at the same time *  * @author Lenovo *  */public class mapentry<k, v> implements Map.entry<k, v> {private K key;private V value;public mapentry ( K key, V value) {This.key = Key;this.value = value;} @Overridepublic K GetKey () {return key;} @Overridepublic V GetValue () {return value;} @Overridepublic v SetValue (v V) {v result = Value;value = V;return result;} public int hashcode () {//XOR differs from 1 to 0return (key = = null? 0:key.hashcode ()) ^ (value = = null? 0:value.hashcode ());} public boolean equals (Object o) {if (! ( o instanceof Mapentry)) return false; Mapentry me = (mapentry) o;return (key = = null?)

Me.getkey () = = Null:key.equals (Me.getkey ())) && (value = = null? me.getvalue () = = Null:value.equals (me.getvalue ()));} Public String toString () {return key + "=" + Value;}}


Package Org.rui.collection2.maps;import Java.util.abstractmap;import Java.util.hashset;import java.util.LinkedList Import Java.util.listiterator;import java.util.map;import java.util.set;/** * Hash for Speed * * The value of the hash is speed. One of the ways to do this is to keep the sort state of the health. Then using the Collections.binarysearch () query * Array does not save the health itself. Instead, a number is generated from the health object, which is used as the subscript for the array. This number is the hash code. * Note: This implementation does not imply that the performance is tuned, it is just to show the various operations of the hash table run, * @author Lenovo * */public class Simplehashmap<k,v> extends Abstract Map<k, v> {static final int size=997;//You can't have a physical geerics array//you can ' t has a physical array of geerics//but you can Upcast to one but you can throw up linkedlist<mapentry<k,v>>[] buckets=new linkedlist[size];//bucket Bucket/*** * for put method Hascode will be called for health. And the result is cast to a positive number.

* In order for the resulting number to fit the size of the bucket array The modulo operator will be modeled according to the size of the array, * assuming that the array is somewhere null, which means that no elements have been hashed to this point. So, in order to save the object that was just hashed to that location * need to create a new LinkedList * */public v put (K key,v value) {V oldvalue=null;int index=math.abs (Key.hashcode () )%size;if (buckets[index]==null) {buckets[index]=new linkedlist<mapentry<k,v>> ();} Linkedlist<mapentry<k, v>> Bucket=buckets[index]; Mapentry<k,v> pair=new mapentry<k,v> (key,value); Boolean found=false; Listiterator<mapentry<k,v>> It=bucket.listiterator (); while (It.hasnext ()) {mapentry<k,v> itm=it.next (); if (Itm.getkey () equals (key)) {Oldvalue=itm.getvalue (); It.set (ItM);//replace old with new Found=true; Break }} if (!found) {buckets[index].add (pair);} return oldValue;} /** * Get calculates the index in the buckets array in the same way as put, * this is very important, because this ensures that two methods can calculate the same position */@Overridepublic V get (Object key) {int Index=math. ABS (Key.hashcode ())%size;if (Buckets[index]==null) return null;for (mapentry<k,v> Ipair:buckets[index]) if ( Ipair.getkey (). Equals (key)) return ipair.geTValue (); return null;} @Overridepublic set<java.util.map.entry<k, v>> entryset () {set<map.entry<k, v>> set=new Hashset<map.entry<k,v>> (); for (linkedlist<mapentry<k,v>> bucket:buckets) {if (bucket==null ) continue;for (mapentry<k,v> mpair:bucket) Set.add (Mpair);} return set;} public static void Main (string[] args) {simplehashmap< String,string> simple=new simplehashmap<string,string> () simple.put ("Cameroon", "Yaounde"); Simple.put ("A "AA"), Simple.put ("B", "BB"), Simple.put ("C", "CC"); System.out.println (simple); System.out.println (Simple.get ("B")); System.out.println (Simple.entryset ());}} /***output:{cameroon=yaounde, C=CC, B=BB, A=aa}bb[cameroon=yaounde, C=CC, B=BB, A=AA] * *




Java hash and hash code discussion, simple HASHMAP implementation hash map run a variety of operation display columns

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.