Previous Next JavaScript must be enabled to correctly display this content

## Using Arrays

Arrays are a sequence of values all of the same type.

When you declare a table field as an array, you use the `ARRAY()` statement.

To define a simple two-field table where the primary key is a UID and the second field contains array of strings, you use the following DDL statement:

    CREATE TABLE myTable (
        uid INTEGER,
        myArray ARRAY(STRING),
        PRIMARY KEY(uid)
    )

`DEFAULT` and `NOT NULL` constraints are not supported for arrays.

To write the array, use `Row.putArray()`, which returns an `ArrayValue` class instance. You then use `ArrayValue.put()` to write elements to the array:

    TableAPI tableH = kvstore.getTableAPI();

    Table myTable = tableH.getTable("myTable");

    Row row = myTable.createRow();
    row.put("uid", 12345);

    ArrayValue av = row.putArray("myArray");
    av.add("One");
    av.add("Two");
    av.add("Three");

    tableH.put(row, null, null);

Note that `ArrayValue` has methods that allow you to add multiple values to the array by appending an array of values to the array. This assumes the array of values matches the array's schema. For example, the previous example could be done in the following way:

    TableAPI tableH = kvstore.getTableAPI();

    Table myTable = tableH.getTable("myTable");

    Row row = myTable.createRow();
    row.put("uid", 12345);

    ArrayValue av = row.putArray("myArray");
    String myStrings[] = {"One", "Two", "Three"};
    av.add(myStrings);

    tableH.put(row, null, null);

To read the array, use `Row.get().asArray()`. This returns an `ArrayValue` class instance. You can then use `ArrayValue.get()` to retrieve an element of the array from a specified index, or you can use `ArrayValue.toList()` to return the array as a Java `List`. In either case, the retrieved values are returned as a `FieldValue`, which allows you to retrieve the encapsulated value using a cast method such as `FieldValue.asString()`.

For example, to iterate over the array created in the previous example:

    TableAPI tableH = kvstore.getTableAPI();

    Table myTable = tableH.getTable("myTable");

    /* Create a primary key for user id 12345 and get a row */
    PrimaryKey key = myTable.createPrimaryKey();
    key.put("uid", 12345);
    Row row = tableH.get(key, null);

    /* Iterate over the array, displaying each element as a string */
    ArrayValue av = row.get("myArray").asArray();
    for (FieldValue fv: av.toList()) {
        System.out.println(fv.asString().get()); }