Array Index of 0 in ColdFusion

Real short post – but something I discovered doing some work on Transfer.

CF Arrays are java.util.Vectors, which means that you can call myNewArray.get(12) on them to get the object at that index.

I kept getting an error saying 'Array 1 index out of bounds', and I couldn't work out why, when I knew I only had one object in the collection.

The thing I totally forgot was, Java arrays are indexed from 0, and ColdFusion arrays are indexed from 1.

So when doing a 'get()' on a Array, you have to remember to refer to your Array as a 0 indexed array, not a normal one like usual… that is if you are brave enough to mess around with Java trickery ;o)

Leave a Comment


  • Jacob Munson | April 5, 2006

    I’ve not been brave enough to do Java stuff from CF yet, but I /have/ been very annoyed with CF’s array indexing. Every other language I’ve used, or currently use, indexes arrays from 0. It really bothers me that CF starts a 1! Of course, if they changed it a ton of code out there would break.

  • Sean Corfield | April 5, 2006

    Pascal uses 1-based arrays, so do FORTRAN, COBOL, Adabas, Rexx etc etc. MATLAB’s HDF functions also use 1-based arrays. PHP lets you create 1-based arrays (although it is 0-based by default). Visual Basic supports 1-based arrays (through the "option base 1" directive) – and all Excel collections are 1-based. And lets not forget that query objects behave like 1-based arrays for good reason: it is more intuitive to have 1st row, 2nd row etc.

    I assume ColdFusion has 1-based arrays because that’s what non-programmers find easier to work with (and originally that was ColdFusion’s target audience, to some extent).

  • PaulH | April 5, 2006

    if you’re prone to that kind of stuff, java months are also zero-based.

  • Matt | May 14, 2007

    Has anyone ever managed to get the indexOf method working with a dynamic variable, it seems to return -1 for me, even if the element does exist.

  • Jeff Dugas | May 30, 2007

    If you’re going to use the underlying (and undocumented) Java methods, I guess you’ll have to bite the bullet and remember to increment (or decrement) by 1 when jumping between CF and Java. Nobody is age 1 the day he/she is born, but who chants ‘We’re number zero!’ after his/her team wins the championships?

    About your question, Paul, would you please post an example of the indexOf() method not ‘working with a dynamic variable’? I use this method from time to time and the only problem I encounter with the get() method is that it is, like most Java string methods, case-sensitive.

  • Jeff Dugas | May 30, 2007

    My apologies, that request for an example was meant to address Matt’s question, not PaulH’s comment.