tags:

views:

4474

answers:

7

I have a Java array such as:

String[] arr = new String[] {"123","doc","projectReport.doc"};

In my opinion the natural way to access would be:

 #set($att_id = $arr[0])
 #set($att_type = $arr[1])
 #set($att_name = $arr[2])

But that it is not working. I have come with this workaround. But it a bit too much code for such an easy task.

#set($counter = 0)
#foreach($el in $arr)
    #if($counter==0)
        #set($att_id = $el)
    #elseif($counter==1)
        #set($att_type = $el)
    #elseif($counter==2)
         #set($att_name = $el)
    #end
    #set($counter = $counter + 1)
#end

Is there any other way?

+1  A: 

You could wrap the array in an java.util.List using java.util.Arrays.asList(Object[] in). The new List object is backed by the original array so it doesn't wastefully allocate a copy. Even changes made to the new List will propagate back to the array.

Then you can use $list.get(int index) to get your objects out in Velocity.

If you need to get just one or two objects from an array, you can also use java.util.Array.get(Object array, int index) to get an item from an array.

Brian
+1  A: 

Brian's answer is indeed correct, although you might like to know that upcoming Velocity 1.6 has direct support for arrays; see Velocity documentation for more information.

Angelo
It's true. In 1.6-beta1 and later, you can just call most ArrayList methods on your array objects. e.g. $array.get(0) $array.set(0, 'foo')
Nathan Bubna
+2  A: 

Just use Velocity 1.6, then you can just do $array.get($index).

In the upcoming Velocity 1.7, you'll be able to do $array[$index] (as well as $list[$index] and $map[$key])

Nathan Bubna
A: 

I ended up using the ListTool from the velocity-tools.jar. It has methods to access an array's elements and also get its size.

Luke Quinane
A: 

there is an implicit counter $velocityCount which starts with value 1 so you do not have to create your own counter.

A: 

Actually, the counter $velocityCount actually starts at 0 when I tested it on my page.

POJD
By default the counter starts at 1, but this can be set to either 0 or 1 in the velocity.properties file.
Marcus
A: 

String[] arr = new String[] {"123","doc","projectReport.doc"}; In my opinion the natural way to access would be:

#set($att_id = $arr[0]) #set($att_type = $arr[1]) #set($att_name = $arr[2])

The value for this can be get by using $array.get("arr",1) because there is no dircet way to get the value from array like $att_id = $arr[0] in velocity. Hope it works :)

Rajesh Chowdary