All about arrays!

Hi there,

This is most likely the best newbie question out there, but I need to ask it. It is about time I actually learn how to properly use Arrays and what they are used for. I see them in all kinds of rendering algorithms, and other things, and I always just added them to the code, rather than created my own usage for them.

So can someone give me an explanation?

Thanks!

  • A

Do you mean vertex object arrays?

if so ill do a post and provide sample code if you like.

What do you mean “properly use?”

An array is an array. You use it where ever you would use an array.

Although Lists are usually more suitable.

EDIT: if you don’t understand what an array is, well: http://en.wikipedia.org/wiki/Array_data_structure

This is why i ask if he / she means VertexBufferArrays… which is more opengl specific…

As lame as this sounds… I mean generally just Arrays. I know to create one… but when would be the proper time to use them? I don’t know, I can’t explain it. For example, randomArray[x][y], what is with 2 seperate []?

Take a look at my edit, under “multidimensional arrays.”

I get what they are and how to create them. I just don’t understand how to know when to use them…

There are no rules. You use them where/how you deem appropriate.
Unsatisfactory answer? It’s the kind of knowledge you gain with experience.

The simplest and most obvious use is indexing: out of this list of things, I want to be able to access any nth one

do you mean when you have seen them in buffered image rendering techniques? well then they are simply a grouping of memory , in detail the array object is the just the first position in the arrays memory location , java of course handles all of this internally but its good knowledge , the type then defines how much memory each subscript takes up , if its an integer its usually 4 bytes , character arrays will use 1 byte per subscript , so if I use arrayname[0] im accessing memory location 0 or arrayname.pointerposition + (0 * numofbytes) , if I said int arrayname[2] and the location in memory that arrayname pointed to was 0,for simplicity, then the byte grouping I would access would be at location 8.
Of course that is in heavy detail , simply put an array is a method of grouping similar data types together , it is a simple and efficient method of programming that is generally coupled with iteration. There are a lot of useful functions surrounding arrays but the most important things about an array are its type , its size and the size of the data type itself , if you have an array of integers so int[] myintslolamazedoge = new int[25]; then you can iterate through it a lot more quickly than say myhuge4kilobyteclass[] omgsuchsize = new myhuge4kilobyteclass[25];. The size of the data does count , if you are putting something into an array ensure that 1, you wont exceed the amount of memory you have available and that you dont go out of bounds.
for iteration use myarray.length , this will return the maximum number of elements the array can contain. So to use this in iteration you would do for(int i = 0; i < myarray.length;i++), use < because i starts at 0 not 1.
2 dimensional arrays are incredibly useful , in java they are so simple to use , unlike in python , c or c++ , they are not accessed as if they were an array of an array , they are more like a chart , a really really big chart , with x along the top and y along the bottom
0,1,2,3,4,5,6,7,8
1,H,I, ,T,H,E,R,E
2 , , , , , , ,
3 , , , , , , ,
4 , , , , , , ,
5 , , , , , , ,

to define one you simply do int[][] my2darry = new int[25][25]; , 3d if you wish int[][][] my3darray = new int[25][25][25];
to access is just as simple, my2darray[0,5] = 2343; my3darray[5,6,1] = (int)“A”;
However , they do have a drawback , they require more time to process this is because the processor cannot simply look in the next location in memory but actually has to look into the location into memory which points to another location in memory , taking up twice as many processor cycles. So be careful and use them when you deem it necessary and performance is not an issue.

Good examples of times to use an array would be in a map , often people may use a hashmap however for smaller maps and for simpler maps its easy to just go Tile[][] map = new Tile[100][100]; , you can also use them for taking apart strings , this is what the string.split() function returns , for instance (hah) , String[] mysplitstring = “ladedadedum”.split(“a”);,where “a” is the regex.
Another use for arrays is storing incredulously large numbers or extremely accurate decimal division , maybe not something you might come into unless you do banking but it can be used.
To be honest though , there are a lot of similar uses for arrays , most of them funnily enough include storing similar data together , its easier to store each persons school record together than have a new object for each one , schoolrecord[] records = new schoolrecord[10]; or schoolrecord a; schoolrecord b; schoolrecord c; etc. I would however get used to them , they are definitely not going anywhere any time soon and make your life a hell of a lot easier, another good example probably a bit closer to home would be storing each vertex of an object you are about to render or are currently performing collision checking on.

Hope that was helpful.

what you may be tripping on is when to use an array vs a List (like an ArrayList or other form of Collection).

The simple truth is before object oriented programming Lists were not arround but arrays where. Array provide a very nice and small way to describe ordered / indexable data.

A list is more flexible and but they do come with a larger memory footprint.

Since arrays have been around a lot longer they are also highly optimized… so if your trying to squeeze as much speed as possible out… thats another factor…

Lists use method calls to get their data and thus are slower.

Now with experience you become pragmatic. The sort of considerations ive listed above to do not make arrays better than lists. In many cases Lists are easier to work with (personal opinion) and easier to maintain. Those factors can out weigh most others. But understanding the pro vs cons of both approaches and when you should use them and why will be a good tool to have in your programming arsenal!

Keep asking questions! dont hesitate. We have all been there and its better to ask then not know.

At least a few of those points are debatable.

A List is a Java-specific (if we’re talking about Java Lists) concept.
They are abstractions around various ways of implementing a dynamic array, using various data structures, as opposed to a static (“normal”) array.

Not sure what you mean about “been around a lot longer,” if you mean arrays have been in since 1.0, and List not until 1.2, then that’s not a huge difference, esp. since both concepts have existed long before Java. You don’t think the JVM guys would leave core stuff like the collections library not “highly optimized?”

Method calls, especially simple ones like get(), etc. are aggressively inlined, and any differences in performance are often negligible.
EDIT: obviously this depends on the implementation, ArrayList vs array will not have a noticeable difference in most use cases, LinkedList etc. is something entirely different.

Lists, being dynamic, generic, etc., are simply almost always easier to use. That should almost always be the deciding factor.

I think the ability to being dynamic is why the lists performance is a shortcoming , being dynamic is great and very useful , however if you are using even just mildly sizeable data that you are going to change the size of quite frequently then the continuous memory reallocations build up , allocating and moving a large portion of data frequently is not efficient , having enough memory allocated in the first place so that you know you probably wont have to reallocate may be more costly in terms of memory usage however it increases performance. That of course depends on how you use it , if its an inventory storer that updates the list every few minutes on average when the player edits it then performance can go out the window on that , if its a list of every vertex on the map (for converting to a floatbuffer) then it will most likely be changing frequently and by varying amounts.

Well, if you have the luxury of knowing how much memory you need ahead of time, then you could use an array.

Or initialize an ArrayList with the proper initial capacity. :point:

that works too. :slight_smile:

“Array” is programmer jargon for what a normal person would call a “list”.

2D arrays normal people call “tables”.

Shameless self-promotion: I wrote a tutorial about arrays here: http://staticvoidgames.com/tutorials/basicConcepts/arrays

That tutorial is geared towards Processing, which you might want to check out if you’re having trouble grokking the basics.

I also find Oracle’s own tutorials both concise & easy: ;D
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

So one thing that no one has mentioned yet (@lcass was closest) and is the most pertinent is that working with arrays of primitive types with Java is the only way you are guaranteed contiguous block of memory. This is important for optimizing algorithms in Java quite often.

Instead of an array or ArrayList of Objects one unpacks the member data in the Object into multiple primitive arrays. In the example below the object in the Android API is “MediaCodec.BufferInfo”. I also store extra relational data across frames that a single MediaCodec.BufferInfo object does not like an index of video key frames which allows me to quickly show updates to the display when a user scrubs video for instance.

The reason my video engine for Android, which you should totally back the Kickstarter: http://kck.st/1sk0lN4 is so darn fast and efficient is because I track everything including frame metadata in primitive arrays. Here is the top of “MediaBuffer” (can be audio / video data or anything really). “MediaFrameInfoArray” holds the metadata arrays.


/**
 * MediaBuffer
 *
 * H264 Stream you should put the SPS in a ByteBuffer with the key “csd-0″ and the PPS with a key of “csd-1″
 */
public final class MediaBuffer extends AbstractDataManager<IComponentManager> implements IMediaBuffer
{
   public final String              mimeType;

   public final MediaFrameInfoArray frameInfoArray;

   public final byte                bufferEncoded[];
   public final int                 bufferEncodedLength;

   public int                       bufferEncodedLimit;

And MediaFrameInfoArray…


/**
 * MediaFrameInfoArray -- Stores arrays of primitive data normally associated with a single MediaCodec.BufferInfo
 * instance. There are helper methods to manipulate the data stored in addition to relative data between frames.
 *
 * %0, 1, 2, 3, 4, %5, 6, 7, 8, 9, %10       frameInfoLength         // % indicates key frame
 *  0, 0, 0, 0, 0,  1, 1, 1, 1, 1, 2         frameToKeyFrame         // stores index to previous key frame
 *  T, F, F, F, F,  T, F, F, F, F, T         frameIsKeyFrame         // stores if frame is a key frame
 *  0, 5, 10                                 keyFrameToFrameIndex    // stores frame index for key frame
 *                                           bufferEncodedPosition   // stores the position of the frame in an associated IMediaBuffer
 */
public final class MediaFrameInfoArray implements IData
{
   public final int        frameContentSize[];
   public final int        frameHeaderOffset[];
   public final int        frameFlags[];
   public final long       framePresentationTimeUs[];

   public final int        frameToKeyFrame[];
   public final boolean    frameIsKeyFrame[];

   public final int        keyFrameToFrameIndex[];

   public final int        bufferEncodedPosition[];

   public final int        frameInfoLength;

   public int              frameInfoLimit;
   public int              keyFrameLimit;

Indeed, the main reason one would abandon many usual “best practices” or comforts is usually performance.

That is (at least partly) why optimization is the root of all evil.

Everything is about optimization , it’s eating into my soul , when I cook an egg I think HOW CAN I OPTIMIZE THE BOILING TIME AND ENERGY USED. all a big government conspiracy if you ask me, they are training us programmers to be efficient so that they can crack the skasis paradigm more quickly! I can protect you , wear a tinfoil hat , sit under a car , sleep under a cow , they all stop them from tracking you.