Java in Notes/Domino Explained: Handling arrays


Probably the biggest source of fustration for LotusScript programmers moving to Java is the fact that arrays cannot be resized in Java once they have been declared. Where in LotusScript we have the Redim keyword there is no equivalent for Java when talking arrays. If you need resizable arrays you should look into the Java Collection API (see the upcoming post “Java Collection API for LotusScript programmers” for more information on the Collection API).

Note: All references to arrays in Java are objects – also references to arrays of the privitive data types (int, long, char etc.).

As mentioned arrays dimensions are fixed in Java once declared and arrays always start at index 0. Notice how the bound has to be one higher than the number of places you need in the array. To declare a simple array with room for 5 Strings you write:

String[] my_strings = new String[5];
my_strings[0] = "abc";
my_strings[1] = "def";
my_strings[2] = "ghi";
my_strings[3] = "jkl";
my_strings[4] = "mno";

Alternatively you may also separate the declaration of the reference from the actual memory allocation.

String[] my_other_strings = null;
my_other_strings = new String[2];
my_other_strings[0] = "abc";
my_other_strings[1] = "def";

A cool thing with Java arrays is that you can use a more condensed syntax and fill the array as you declare it. It is a great way to avoid manually having to specify the dimensions of the array. The below code produces the same array as above (notice the use of curly braces).

String[] my_strings = {"abc", "def", "ghi", "jkl", "mno"};

This doesn’t just work for Strings but can be equally applied to other types of objects:

Object[] my_objects = {"abc", new java.util.Date(), new java.lang.Object()};

The reference to an array is kind of special in Java since it has a special member variable called length to help in looping the array. The basic construct for looping an array in Java is a for-loop just like in LotusScript. In the Java versions employed by Notes/Domino 7 and below there is no forall type loop.

String[] my_strings = {"abc", "def", "ghi", "jkl", "mno"};
for (int i=0; i<my_strings.length; i++) {
   System.out.println("Index " + i + ": " + my_strings[i]);
}

When working with arrays you really should be using the length member variable when looping arrays. If not you’ll most likely at some point run into the java.lang.ArrayIndexOutOfBoundsException which is an unchecked exception.