How to access/get the size of an array/collection in velocity templates? How to access/get the size of an array/collection in velocity templates? java java

How to access/get the size of an array/collection in velocity templates?


I've never used Velocity, but its VTL reference guide says that calling a method is done using $customer.getAddress() or ${purchase.getTotal()}. So I would use ${myArrayList.size()}.


A collection can be accessed like any other object, so $collection.size() will contain a value.

Arrays are special cased to behave like List, so though $array.length doesn't work, $array.size() works.

In older versions of Velocity (pre 1.6) you'd use ListTool and ArrayTool.


Quote from the developer guide:

Object [] Regular object array, not much needs to be said here. Velocity will internally wrap your array in a class that provides an Iterator interface, but that shouldn't concern you as the programmer, or the template author. Of more interest, is the fact that Velocity will now allow template authors to treat arrays as fixed-length lists (as of Velocity 1.6). This means they may call methods like size(), isEmpty() and get(int) on both arrays and standard java.util.List instances without concerning themselves about the difference.

So using size() works equally well on java.util.List and java arrays.