Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ES6 Hash Map on any object without maintaing a reference (I.e. Java hashcode)

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?

like image 239
Upio Avatar asked Feb 06 '15 02:02

Upio


People also ask

How does get () method of HashMap works if two keys have the same hashCode?

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).

Can 2 different objects have same hashCode?

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.

How will you retrieve value object if two keys have the same hashCode?

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 ...

How hashCode () and equals () methods are used in HashMap?

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.


1 Answers

  • If the lack of object identity stems from a serialize-deserialize roundtrip just give them a unique ID that survives that and use that ID as key
  • calculate a key from a subset of its properties if you can be certain that the remaining properties either depend on that subset or are irrelevant to your operation
  • implement your own hash map and object hashing. this can get tricky with host objects but should be fairly simple with JSON-compatible data
  • JSON-encode before each get or set. It's quite inefficient and only works with JSON-serializeable objects. But easier to implement than the previous option
like image 196
the8472 Avatar answered Sep 18 '22 01:09

the8472