Array list access with array index notation

In Gosu, you can access elements of Java language array lists by using array index notation. You can iterate through Java array lists in a for loop the same as a Gosu array. The following code creates a Java array list, populates the list, and updates one element in the list by using array index notation. Then the code uses a for loop to iterate through the elements of the list and print them.

// Create a Java array list. 
var list = new java.util.ArrayList()

//Populate the Java list with values.
list.add("zero")
list.add("one")
list.add("two")
list.add("three")
list.add("four")

//Assign a value to a element of the Java list.
list[3] = "threeUPDATED"

//Iterate through the Java list the same way as a Gosu array.
for (element in list) {
  print(element)
}

The output for this code is:

zero
one
two
threeUPDATED
four

In many situations, using collection classes, such as java.util.ArrayList or java.util.HashMap, is a better choice than using Gosu arrays. For example, the sizes of lists and maps grow and shrink as you add and remove members from them. The ArrayList and HashMap classes are the native Java array lists and hash maps. Gosu adds enhancement methods to these types or their parent classes/interfaces, such as the interface java.util.List.

See also