Hash algorithm implemented in Java

Hash

  Hash, generally translated to do a "hash", also has a direct transliteration of "hash", that is, the arbitrary length input, through a hash algorithm, converted into a fixed-length output, the output is the hash value. The address is stored as the hash value of the data, this conversion is a compression map, simply means that A message of arbitrary length is compressed to a fixed length message digest function. Data search key (e.g. K) when, and if the record key equal to the present structure, the location must be stored in the F (K) is on. Thus, no direct comparison can be made by check records. We call this correspondence between the hash function f (Hash function), established by this event as a hash table.

  As described above, according to the method of the hash function f (key) and the conflict will be mapped to a set of keywords on a finite set of consecutive addresses (interval), and concentrated to address keywords "like" as the storage location records in the table, this table will be called a hash table, the mapping process is called making a hash or hash table, the resulting storage location called a hash address.

Hash collision 

  May get different keywords the same hash address, key1 ≠ key2, and f (key1) = f (key2), a phenomenon known as hash conflict. That is: key1 f (key1) obtained by a hash address to store key1, empathy, key2 find their corresponding hash address has been occupied key1.

Solution (a total of four):

1. Method OpenAddressed

  The so-called open-addressing method is that once a conflict, and went looking for the next empty hash address, as long as the hash table is large enough, empty hash address can always find and record stores.

  Open Addressing Method: Hi = (H (key) + di) MOD m, i = 1,2, ..., k (k <= m-1), where H (key) to the hash function, m is the hash table length, increments DI sequence, the following three can be emulated:

    1). di = 1,2,3, ..., m-1, said re-hash linear probe;

    2). di = 1 ^ 2, (- 1) ^ 2,2 ^ 2, (- 2) ^ 2, (3) ^ 2, ..., ± (k) ^ 2, (k <= m / 2), said secondary detect re-hash;

    3). di = pseudo random number sequence, and then detecting said pseudo-random hash.

  Resolve conflicts by addressing law practice is open: When a collision occurs, use some detection technology (linear detection method, secondary detection method (to solve the problem of accumulation of linear probe), the same random detection method (and the second detection principle, not is the same: the secondary detection to skip value, the hash address is a random variable hop length detected value)) is formed in a probe sequence hash table. This sequence along find cell by cell until it finds a given keyword or across an open address (i.e., the location is empty) can be inserted so far.

  For example, we set is {keyword} 12,67,56,16,25,37,22,29,15,47,48,34, table length of 12. We use a hash function f (key) = key mod l2

  {} When calculating the number of front 12,67,56,16,25 S, they are not in conflict hash address, direct deposit:

    

  Calculating key = 37, it was found f (37) = 1, this time to the 25 position of conflict is located.

  Then we apply the above equation f (37) = (f (37) +1) mod 12 = 2. 37 will then be stored in the position labeled 2:

  

2. re-hash

  Then called hashing double hashing, a plurality of different Hash function, when a conflict occurs, using a second, third, ...., And the like to calculate the hash function address until no conflict. Although less prone to aggregation, but it increases the computation time.

3. Chain address method (Java hashmap is to do so)

  The basic idea is that the chain address method: hash table for each node has a next pointer, hash table plurality of nodes may constitute a singly linked list with the next pointer, keywords all nodes in a single linked with synonyms the list, such as:

  With m = 5, H (K) = K mod 5, the key value sequence Example 5, 21, 17, 9, 15, 36, 41, 24, according to the chain address method established by the hash table below It shows:  

4. Establish a common overflow area

  The basic idea of ​​this method is: the hash table is divided into two parts, the base table and overflow table, any table of elements and basic conflict, always populated overflow table.

Code:

  Person class:

    About the Java hashCode method, please see:

    https://www.cnblogs.com/dolphin0520/p/3681042.html

 

. 1  Package my.hash;
 2  
. 3  / ** 
. 4  * the Person class
 5  * equals and hashCode method override methods
 . 6  * hashCode method of calculating the object's hash code
 . 7  * in the Java object has a hash code for each
 8  * @author ASUS
 . 9  *
 10   * / 
. 11  
12 is  public  class the Person {
 13 is      Private String name;
 14      Private  int Age;
 15      
16      // SET and get methods 
. 17      public String getName () {
 18 is          return name;
 . 19     }
20     public void setName(String name) {
21         this.name = name;
22     }
23     public int getAge() {
24         return age;
25     }
26     public void setAge(int age) {
27         this.age = age;
28     }
29     
30     //构造器
31     public Person(String name,int age){
32         super();
33         this.age=age;
34         this.name=name;
35     }
36     
37     //输出方法
38     public String toString() {
39         return "Person [name="+name+",age="+age+"]";
40     }
41     
42     //重写hashcode方法
43     public int hashCode() {
44         final int prime=31;
45         int result=1;
46         result=prime*result+age;
47         result=prime*result+((name==null)?0: name.hashCode ());
 48          return Result;
 49      }
 50      
51 is      / * override method equals
 52       * must override hashCode method when override this method, since an object to ensure that map to the same memory address
 53       * / 
54      public  Boolean the equals (Object Object) {
 55          IF ( the this == Object) {
 56 is              return  to true ;
 57 is          }
 58          IF (Object == null ) {
 59              return  to false ;
 60          }
 61 is          IF (getClass () =!object.getClass()){
62             return false;
63         }
64         Person other=(Person)object;
65         if(age!=other.age){
66             if(other.name!=null){
67                 return false;
68             }
69         }else if (!name.equals(other.name)) {
70             return false;
71         }
72         return true;
73     }
74 }

  About getClass method of the Java code, more information:

  https://blog.csdn.net/mark_to_win/article/details/38757259

  Test categories:

 1 package my.hash;
 2 
 3 import java.util.HashSet;
 4 
 5 public class Test {
 6     public static void main(String[] args) {
 7         //构造6个person对象
 8         Person p1=new Person("sam", 10);
 9         Person p2=new Person("amy", 13);
10         Person p3=new Person("lili", 22);
11         Person p4=new Person("daming", 34);
12         P5 = the Person new new the Person ( "a", 2 );
 13 is          the Person P6 = new new the Person ( "b", 2 );
 14          
15          // output values of a and b hashcode 
16          System.out.println ( "a value of the hashcode : "+ p5.hashCode () +" b hashcode value of: "+ p6.hashCode ());
 . 17          
18 is          // define a HashSet, the Person object stored in the set 
. 19          HashSet <Person> sET = new new HashSet < Person> ();
 20 is          
21 is          // will add HashSet Person object set 
22 is          set.add (P6);
 23 is          set.add (P5);
 24          set.add (P4);
 25         set.add (P3);
 26 is          set.add (P2);
 27          set.add (P1);
 28          
29          // traverse HashSet, hashCode p5 and p6 when the same, but added to the set of SET, the bottom layer solution described hashset the problem of hash conflict. 
30          for (the Person Person: SET) {
 31 is              System.out.println (Person);
 32          }
 33 is      }
 34 is }

  operation result:

  

Guess you like

Origin www.cnblogs.com/wangjiong/p/11220583.html