Recently, I often use some of the small details that I have seen before but have not actually realized, and I have a deep feeling (mastering a technology is not enough to look at it again, not enough for a time, and it is far from enough ...). ),
Let's go straight to the code.
Attributeresult
1 Public classAttributeresult {2 String value;3 String result;4 5 PublicAttributeresult () {6 7 }8 9 PublicAttributeresult (string value, string result) {Ten This. Value =value; One This. result =result; A } - - @Override the Public Booleanequals (Object o) { - if( This==o) - return true; - if(O = =NULL|| GetClass ()! =O.getclass ()) + return false; -Attributeresult Attributeresult =(Attributeresult) o; + if(Attributeresult.result = =NULL|| Attributeresult.value = =NULL) A return false; at if(Value.equals (Attributeresult.value) &&result.equals (attributeresult.result)) - return true; - return false; - } - - @Override in Public inthashcode () { - returnValue! =NULL? Value.hashcode (): 0; to } + Public Static voidMain (string[] args) { -Map<attributeresult, integer> valuelist =NewHashmap<attributeresult, integer>(); theValuelist.put (NewAttributeresult ("Mim", "yes"), 20); *Valuelist.put (NewAttributeresult ("Mim", "No"), 1); $Valuelist.put (NewAttributeresult ("xunying", "yes"), 60);Panax NotoginsengValuelist.put (NewAttributeresult ("xunying", "No"), 2); -Valuelist.put (NewAttributeresult ("Mini", "No"), 2); the if(Valuelist.containskey (NewAttributeresult ("xunying", "Yes"))){ +SYSTEM.OUT.PRINTLN ("presence"); A}Else{ theValuelist.put (NewAttributeresult ("Mini", "yes"), 30); + } - } $ $}
The operating result must be: presence
In this case the Attributeresult class overloads the Hascode () method and the Equals () method so that the lookup exists, and if not overridden, ContainsKey () returns the inevitable false, because by default:
In HashMap
, the key
comparison order of lookups is:
- Calculates the object's
Hash Code
, see if it exists in the table.
- Checks
Hash Code
if the object in the corresponding location is equal to the current object
The first step is to use the hashCode()
method, and the second step is to use the equals()
method.
In these two steps, the two methods of the class are called by default in the absence of overloading, Object
and in Object
, Hash Code
the calculation is based on the address of the object.
- Overloading is for the same
hashCode()
key
, can get the same Hash Code
, so HashMap
you can navigate to our designated key
.
- Overloading
equals()
is to HashMap
show that the current object and the key
object being saved are equal so that we actually get the key
corresponding key-value pair.
The above summary is derived from 1190000002655085, thanks
Java custom type Lookup as key for Hasmap