Java Reference
In-Depth Information
Using Lists, Maps, and Sets
Nashorn does not provide built-in objects to represent general-purpose maps and sets.
You can use any object in Nashorn as a map whose keys are strings. It is possible to create
objects in Nashorn to represent maps and sets. However, doing so will be like reinventing
the wheel. The Java programming language provides many types of collections, including
maps and sets. You can use those collections in Nashorn directly. Please refer to
Chapter 6
for more details on how to use Java classes in Nashorn scripts. I will discuss Java
List
s
and
Map
s in this section that are given special treatment in Nashorn.
Using a Java List as a Nashorn Array
Nashorn allows you to treat a Java
List
as a Nashorn array to read and update elements
of the
List
. Note that it does not let you add elements to the
List
using the array indexes.
You can use indexes to access and update elements of the
List
. Nashorn adds a
length
property to instances of Java
List
, so you can treat the
List
as an array-like object.
Listing 7-4 shows you an example of using Java
List
in a Nashorn script.
Listing 7-4.
Accessing and Updating a java.util.List as an Array Object in Nashorn Script
// list.js
var ArrayList = Java.type("java.util.ArrayList");
var nameList = new ArrayList();
// Add few names using List.add() Java method
nameList.add("Lu");
nameList.add("Do");
nameList.add("Yu");
// Print the List
print("After adding names:");
for(var i = 0, len = nameList.size(); i < len; i++) {
print(nameList.get(i));
}
// Update names using array indexes
nameList[0] = "Su";
nameList[1] = "So";
nameList[2] = "Bo";
Search WWH ::
Custom Search