I've been experimenting with ES6 Map in io.js and realized that I can't do the following:
var map = new Map()
map.set( {key:"value"}, "some string");
map.get( {key:"value"} ); // undefined. I want "some string"
This is because {key:"value"} === {key:"value"} is false.
I need to be able to use an object as a key but not require the ACTUAL object to lookup the value like how java HashMap uses hashcode and equals. Is this possible?
If two keys are the same ( equals() returns true when you compare them), their hashCode() method must return the same number. If keys violate this, then keys that are equal might be stored in different buckets, and the hashmap would not be able to find key-value pairs (because it's going to look in the same bucket).
1) If two objects are equal (i.e. the equals() method returns true), they must have the same hashcode. 2) If the hashCode() method is called multiple times on the same object, it must return the same result every time. 3) Two different objects can have the same hash code.
If two key have the same hashCode (which doesn't mean they are identical), they will be stored in the same linked list inside the HashMap (assuming you are asking about HashMap s), and the value to be returned will be determined be comparing all the keys that have the same hashCode with the requested key (using equals ...
In HashMap, hashCode() is used to calculate the bucket and therefore calculate the index. equals() method: This method is used to check whether 2 objects are equal or not. This method is provided by the Object class. You can override this in your class to provide your implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With