Java Reference
In-Depth Information
Inside printInts():[1, 2, 3]
Inside printInts():[1, 0, 3]
Inside printInts():[1, 1, 0, 10]
Inside printDoubles(double[]):[10.89, NaN, 3.0]
Inside printList():[10.89, Hello, 3]
Inside printMap():
key = 0, value = 10.89
key = 1, value = Hello
key = 2, value = 3
Sometimes it is not possible for Nashorn to automatically convert a Nashorn array to
a Java array automatically—particularly when Java methods are overloaded. Consider the
following code that throws an exception:
var Arrays = Java.type("java.util.Arrays");
var str = Arrays.toString([0, 1, 2]); // Throws a java.lang.
NoSuchMethodException
The Arrays.toString() method is overloaded and Nashorn cannot make a decision
which version of the method to call. In this case, you must either explicitly convert the
Nashorn array to the specific Java array type or choose the specific Java method to call.
The following code shows both approaches:
var Arrays = Java.type("java.util.Arrays");
// Explicitly convert Nashorn array to Java int[]
var str1 = Arrays.toString(Java.to([1, 2, 3], "int[]"));
// Explicitly choose the Arrays.toString(int[]) method to call
var str2 = Arrays["toString(int[])"]([1, 2, 3]);
Summary
An array in Nashorn is a specialized object, called an Array object, which is used to
represent an ordered collection of values. An Array object treats certain property names
in a special way. If a property name can be converted to an integer that is between 0 and
2 32 -2 (inclusive), such a property name is known as an array index and the property is
known as an element . An Array object has a special property called length that represents
the number of elements in the array.
An array can be created using an array literal or using the constructor of the Array
object. An array literal is a comma-separated list of expressions enclosed in brackets that
constitute the elements of the array. Arrays in Nashorn are variable-length and may be
dense or sparse. Elements in an array can also be of different types.
 
Search WWH ::




Custom Search