HASHMAP is not thread safe
The following figure shows the realization of HashMap's Get method, which is judged by the hashcode and Equals method.
It is possible to implement the equality criteria for custom object by overriding the Hashcode and equals methods of the class, with the complete code as follows
Book.java
Package com.shc.map;
public class Book {
private String title;
Public book (String title) {
super ();
this.title = title;
}
Public String GetTitle () {return
title;
}
public void Settitle (String title) {
this.title = title;
}
@Override public
int hashcode () {return
title.hashcode ();
}
@Override public
boolean equals (Object obj) {
Boolean flag = false;
if (obj instanceof book) {book Book
= (book) obj;
Flag = This.title.equals (Book.title);
}
Return flag
}
}
Hashmaptest.java
Package com.shc.map;
Import Java.util.HashMap;
Import Java.util.Map;
Import Org.junit.Test;
public class Hashmaptest {@Test the public void TestHashMap1 () {map map = new HashMap ();
String sss = "AAA";
String yyy = "BBB";
Book AAA = new book (SSS);
Book BBB = new book (YYY);
Map.put (AAA, "aaaaaaaaaaaaaaaaaa");
Map.put (BBB, "bbbbbbbbbbbbbbbbbb");
Object content = Map.get (AAA);
Output AAAAAAAAAAAAAAAAAA System.out.println (content);
Change object's attribute, its hashcode is invariable, Object memory address is invariable aaa.settitle ("Xwegwear");
Content = Map.get (AAA);
Output AAAAAAAAAAAAAAAAAA System.out.println (content);
Hashcode different Book CCC = new book (YYY);
Content = Map.get (CCC);
Output null System.out.println (content);
/** * After rewriting the book's Hashcode and Equals method * * @Test public void TestHashMap2 () {map map = new HashMap ();
String sss = "AAA";
String yyy = "BBB";
Book AAA = new book (SSS);
Book BBB = new book (YYY);
Map.put (AAA, "aaaaaaaaaaaaaaaaaa");
Map.put (BBB, "bbbbbbbbbbbbbbbbbb");
Object content = Map.get (AAA);
Output AAAAAAAAAAAAAAAAAA System.out.println (content);
Changing the properties of an object Aaa.settitle ("Xwegwear");
Map.get, the acquired AAA Hashcode has changed, has not been taken to AAA content = Map.get (AAA);
Output null System.out.println (content);
Hashcode same Book CCC = new book (YYY);
Content = Map.get (CCC);
Output bbbbbbbbbbbbbbbbbb System.out.println (content);
The string "BBB" and the variable yyy hashcode the same book TTT = The new book ("BBB");
Content = Map.get (TTT);
Output bbbbbbbbbbbbbbbbbb System.out.println (content);
}
}