Java Reference
In-Depth Information
There are two types of arrays: dense and sparse. In a dense array, the indexes of all
elements are contiguous. Java arrays are always dense arrays. In a sparse array, indexes
of all elements may not be contiguous. Nashorn arrays are sparse arrays. For example,
you can have an array in Nashorn that has an element at index 1000 without having any
elements from indexes 0 to 999.
Unlike in Java, arrays in Nashorn does not have a type. The elements in an array can
be of mixed types—one element can be a Number, another a String, another an Object,
and so on. Nashorn also supports typed-arrays, but they work quite differently than Java
arrays. I will discuss typed arrays in the Typed Arrays section in this chapter.
Creating an Array
There are two ways to create an array in Nashorn:
Using an array literal
Array object
Using the
Using an Array Literal
An array literal is an expression that represents an Array object. An array literal is also
known as an array initializer . It is a comma-separated list of expressions enclosed in
brackets; each expression in the list represents an element of the array. The following are
examples of using array literals:
// An array with no elements, also called an empty array
var emptyArray = [];
// An array with two elements
var names = ["Ken", "Li"];
// An array with four element. Elements are of mixed types.
var misc = [1001, "Ken", 1003, new Object()];
// Print the array length and its elements
print("Array's length: " + emptyArray.length + ", elements: " + emptyArray);
print("Array's length: " + names.length + ", elements: " + names);
print("Array's length: " + misc.length + ", elements: " + misc);
Array's length: 0, elements:
Array's length: 2, elements: Ken,Li
Array's length: 4, elements: 1001,Ken,1003,[object Object]
 
Search WWH ::




Custom Search