Search code examples
javascriptjavarhino

java and javascript - Access to a Map


I am using rhino to execute a javascript code in my Java program. I can't iterate the map in the javascript.

Java side:

private final Map<Long, ClassEmployees > employees ;
...
employees.put (numEmployees, new ClassEmployees());
...

JavaScript side:

keys = employees.keySet();
for (var i in keys) {
  print ("++ " + i);   // ===> print the method ??? Strange...no?
}

===> Output :

++ getClass
++ iterator
++ toArray
++ addAll
++ remove
++ equals
++ containsAll
++ class
++ hashCode
++ contains
++ wait
++ add
++ size
++ clear
++ isEmpty
++ notify
++ empty
++ retainAll
++ toString
++ notifyAll
++ removeAll


Solution

  • Your keys variable holds a reference to a Java Set object, but the JavaScript's for in construct does not really know how to iterate over it, and thus treats it just like any other object.

    The for...in statement iterates over the enumerable properties of an object

    The Set object methods are enumerable properties of it, hence that is what you get.

    To iterate over the underlying values of your Set, you should use an explicit iterator (just like in Java), or simply convert it to an array, like that:

    for each (var i in keys.toArray() ) {
         //...        
    }