Is there any way to implement equals and hashCode using Nashorn javascript?
Attila Szegedi
attila.szegedi at oracle.com
Wed Oct 8 16:33:22 UTC 2014
Hi Arseniy,
short answer: it isn't possible.
The issue here is that your equals() methods aren't receiving the JavaScript objects that provide the state; rather, they're receiving "jdk.nashorn.javaadapters.java.lang.Object" adapter instances, which are encapsulating the JavaScript object and exposing its public interface (which, in this case, is java.lang.Object) You would need to access the JS object behind the "other" adapter, but there is currently no facility for that.
Attila.
On Aug 20, 2014, at 5:17 PM, Arseniy Kovalchuk <ars.kov at gmail.com> wrote:
> var HashMap = java.util.HashMap;var JInteger = java.lang.Integer;var
> JObject = Java.extend(java.lang.Object);
> var createVertex = (function() {
> var
> _equals = function(other) {
> print(this + ' vs ' + other);
> return this._from === other.from;
> };
> _hashCode = function() {
> var hashCode = JInteger.hashCode(this._from);
> print(hashCode);
> return hashCode;
> };
> return function(from, cost) {
> return new JObject() {
> _from : from,
> _cost : cost,
> equals : _equals,
> hashCode : _hashCode,
> }
> }})();
> var JSVertex = function(from, cost) {
> return new JObject() {
> _from : from,
> _cost : cost,
> equals : function(other) {
> print(this + ' vs ' + other);
> return this._from === other._from;
> },
> hashCode : function() {
> var hashCode = JInteger.hashCode(this._from);
> print(hashCode);
> return hashCode;
> }
> }}
> var v1 = JSVertex(1, 10);var v2 = JSVertex(1, 20);//var v1 =
> createVertex(1, 10);//var v2 = createVertex(1, 20);var v3 =
> createVertex(1, 20);
> print(v1.class === v2.class); // returns true
> print(v2.class === v3.class); // returns truevar hm = new HashMap();
> hm.put(v1, 10);
> hm.put(v2, 21);
> print("HashMap size: " + hm.size()); // Prints 2, but I'd like to see 1
> print("HashMap contains: " + hm.containsKey(v3)); // Prints false
More information about the nashorn-dev
mailing list