Test Case:
Package Test;import org.junit.test;import Po. Person;import java.util.hashmap;import java.util.identityhashmap;import java.util.map;/** * Created by Administrator On 2015/9/16. */public class TestMap {/** * map inserts the same key question, value will not overwrite */@Test public void TestMap () {//hashmap in K EY content is the same, then overwrite map<string,object> map1 = new hashmap<> (); Map1.put ("Zhang San", 1); Map1.put ("Zhang San", 2); Map1.put (New String ("Zhang San"), 3); According to the string attribute, the three items are the same, the first two addresses are the same map1.put ("John Doe", 4); For (String S:map1.keyset ()) {System.out.println (s+ "======" +map1.get (s)); }/** Results * Zhang San ======3 John Doe ======4 */System.out.println ("======================== ============="); The memory address of key in Identityhashmap must be identical to overwrite map<string,object> map2 = new identityhashmap<> (); Map2.put ("Zhang San", 1); Map2.put ("Zhang San", 2); Map2.put (New String ("Zhang San"), 3);//Map2.put ("John Doe", 4); for (String S:map2.keyset ()) {System.out.println (s+ "= = =" +map2.get (s)); }/** * John Doe ====4 Zhang San ====2 Zhang San ====3 */System.out.println ("===================== ================"); map<person,object> map3 = new identityhashmap<> (); Map3.put (New person ("Zhang San", 11), 1); Map3.put (New person ("Zhang San", 11), 3); Map3.put (New person ("John Doe", 11), 4); for (person S:map3.keyset ()) {System.out.println (s.tostring () + "= =" +map3.get (s)); }/** * [Email protected]====1 [email protected]====4 [email protected]====3 */System.out.println ("====================================="); person person = new Person ("Zhang San", 11); Person Person2 = new Person ("Zhang San", 11); System.out.println (Person.equals (Person2)); }}
package po;/** * Created by Administrator on 2015/9/16. */public class Person {in T ID; String name; int age; @Override public String toString () {return "person{" + "id=" + ID + ", name= '" + name + ' \ ' + ', age= ' + Age + '} '; } @Override public boolean equals (Object o) {if (this = = O) return true; if (o = = NULL | | getclass ()! = O.getclass ()) return false; Person person = (person) o; if (id! = person.id) return false; if (age! = Person.age) return false; Return! (name! = null?!name.equals (person.name): Person.name! = null); } @Override public int hashcode () {int result = ID; result = * result + (name! = null? Name.hashcode (): 0); result = * result + age; return result; The public person (String Name,int age) {this.name=name; This.age=age; }}
Map in Java Insert the same key