Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to access an array inside Velocity?

Tags:

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?

like image 885
Sergio del Amo Avatar asked Oct 10 '08 15:10

Sergio del Amo


People also ask

How do you access an array index?

Array indexing is the same as accessing an array element. You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.

Where is an array stored in memory?

Memory is allocated in Heap are for the Array in Java. In Java reference types are stored in the Heap area. As arrays are also reference types, (they can be created using the “new” keyword) they are also stored in the Heap area.

Can I set an element in an array to null?

Java arrays are fixed-size. You need to use an ArrayList for that. If you set an element to null, the array will still have the same size, but with a null reference at that point.

What factors does Java consider when determining how much memory an array should occupy?

The memory allocation for an array includes the header object of 12 bytes plus the number of elements multiplied by the size of the data type that will be stored and padding as needed for the memory block to be a multiple of 8 bytes.


1 Answers

You can use use Velocity 1.6: for an array named $array one can simply do $array.get($index).

In the upcoming Velocity 1.7, one will be able to do $array[$index] (as well as $list[$index] and $map[$key]).

like image 128
Nathan Bubna Avatar answered Sep 22 '22 07:09

Nathan Bubna