PackageThinkinginjava;ImportJava.util.HashMap;/** Test the effect of the Equals method and the Hashcode method of the object when manipulating an object in a Hashcode-based collection (HashSet, HASHMAP, HashTable) **/classMapItem2 {PrivateString title; PublicMapItem2 (String title) { This. title =title; } Public voidSettitle (String title) { This. title =title; } @Override Public inthashcode () {returnTitle.hashcode (); }} Public classTestequalsandhashcode { Public Static voidMain (string[] args) {//to add an object to the HashMap /** 1. Hashcode of the calculated object * 2. The object is stored in the corresponding array according to the calculated Hashcode * 3. If two objects are calculated with the same hashcode, * then the E The Quals method determines whether two objects are not equal. * If the Equals method returns True, this overwrites an existing object. * Otherwise do the next action * 4. The two objects are stored on the linked list with the hashcode corresponding array element as the header **/HashMap HM=NewHashMap (); MapItem2 mi=NewMAPITEM2 ("") ; //System.out.println ("HashMap object hashcode:" + mi.hashcode ());Hm.put (HM, "XX") ; //get a value from HashMap using the Get method of HashMap /** 1. Calculate its hash value according to the object passed in, and find the corresponding array position. * 2. The Equals method is used to determine whether the value on the array position is equal to the value. * 3. Equal return value, otherwise null is returned. */ /** Test: Use hashcode of the title property of the object as the return value of the hashcode, * then put the object in the map, then change the title and then take the value from the map*/HashMap HM2=NewHashMap (); MAPITEM2 mi2=NewMAPITEM2 ("xxx") ; Hm2.put (mi2,"XXX") ; Mi2.settitle ("yyyy");//after you reset the title value, you can no longer get the XXX value because the hash value calculated at Get is changedSystem.out.println (Hm2.get (mi2)); }}
Java tests for hashcode and equals