| 1. |
Why is a string used as a HashMap key in Java? |
|
Answer» Basically, the HashMap object can store key-value pairs. When creating a HashMap object and storing a key-value pair in that object, you will notice that while storing, the hash code of the key will be calculated, and its calculated value will be placed as the resultant hash code of the key. Now, when the key is passed to fetch its value, then the hash code of the key is calculated again, and if it's equal to the value of the hash code initially calculated, the initial value placed as the resultant hash code of the key is RETRIEVED or fetched. Let's say we utilized a variable as a key to store DATA and then changed the value of that variable. In this case, since we have altered the key, the hash code calculated of the current key will not match the hash code at which its value was ORIGINALLY stored. This makes RETRIEVAL impossible. String values are immutable, so once they've been created, they can't be changed. As a result, it is recommended to use Strings as HashMap KEYS. |
|