All other possible attributes of Account class can be changed on runtime.If we want to use any class as a key in a hashmap then it should be immutable. I have overridden the hashcode and equals method such that it uses only account number to verify the uniqueness of Account object. In this example, I have created an Account class with only two fields for simplicity. HashMap Custom Key ExampleĪn example is always better for demonstration, right? Then let’s have one. But, you must make sure you are honoring the contract with equals() also. This can be done by overriding the hashCode() method. If you want to make a mutable object as a key in the hashmap, then you have to make sure that the state change for the key object does not change the hashcode of the object. and it is the answer to the question of why string is a popular hashmap key in java?īut remember that immutability is recommended and not mandatory. This is the main reason why immutable classes like String, Integer or other wrapper classes are a good key object candidate. But, again, such a class must honor the hashCode() and equals() methods contract. So it actually solves almost all the problems in one go. ![]() Immutability ensures that we will get the same hashcode every time, for a key object. We should Make the HashMap’s Key Immutableįor the above basic reasoning, key objects are suggested to be immutable. So, next time you call the object’s hashCode() method, JVM recalculates the hashcode for that object. When we modify an object’s state, JVM set a flag that the object is modified and hashcode must be AGAIN computed. On runtime, JVM computes hashcode for each object and provides it on demand. The old key-value pair is not reachable, and so It is a case of a memory leak. If, accidentally, the hashcode of the key object changes after we have put a key-value pair in the map, then it’s almost impossible to fetch the value object back from the map because we don’t know in which bucket we had put the key-value in past. ![]() Different hashcode values may be referring to the different bucket locations. What if Changing the Key’s HashCode is Allowed?Īs stated above, the hashcode helps in calculating the bucket position for storing the key-value pair in the Map. Overriding the the hashCode() is generally necessary whenever equals() is overridden to maintain the general contract for the hashCode() method, which states that equal objects must have equal hash codes.Ģ. This value is used to locate the bucket location in the Map. ![]() hashcode() – returns a unique integer value for the key in runtime. ![]() Override to provide the logic to compare two keys.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |