I’m using jshashtable.js by Tim Down. I’m populating two different hashtables using the following Key object which implements both hashCode() and equals():
function Key(did, oId){
this.dId = dId;
this.oId = oId;
this.hashCode = function(obj) {
//alert("hashCode: " + this.dId+"-"+this.oId);
return this.dId+"-"+this.oId;
}
this.equals = function(obj) {
//alert("obj.dId: "+ obj.dId + " this.dId: " + this.dId + "\nobj.oId: " + obj.oId + " this.oId: " + this.oId);
//alert("dId compare: " + obj.dId == this.dId + " oId compare: " + obj.oId == this.oId);
alert("obj instanceof Key: " + obj instanceof Key);
return (obj instanceof Key) &&
(obj.dId == this.dId) &&
(obj.oId == this.oId);
};
}
I’m then iterating over one hashtable and using containsKey() in order to decide if this key exists in the hashtable that I’m iterating over and adding the new Key/Value pair, or not, based on the boolean returned from containsKey(). The problem that I’m seeing is that although the hashCode() method alerts the same string, the object equals() is returning false, so it always thinks it has a new Key.
I tried using a literal string as the key also dId+’-‘+oId, which I thought should work too. When it didn’t, I tried the object with hashCode() and equals() which also doesn’t seem to work.
Perhaps worth noting is that oId could be a string “5” or a number 5. However, I thought that since Javascript isn’t strongly typed, that difference shouldn’t matter – especially since, when concatenated with the dId+’-‘ it should become a string.
Any ideas on why the comparisons don’t seem to be working?
Thanks in advance
There are two minor problems in the code you’ve posted:
dIdrather thandid, but I assume that must be a typo in your example here because the code here throws immediately whenKeyis called;alert("obj instanceof Key: " + obj instanceof Key);is misleading: it alertsfalsebecause operator precedence makes it effectively("obj instanceof Key: " + obj) instanceof Key.Other than that I can’t find a problem and it seems to work:
… alerts 1, as expected.