Pages

Tuesday, June 12, 2012

Arrays


In the Java language, the arrays are quite simple. You must instanciate it before operate with, and specifie its size. Then you can set a value to each index. Every index must be set as the original data type, if it must to be instancied, here it must also be instancied.

Here is an example:
byte[] a = new byte[3];
a[0] = 3;
a[1] = 3;
a[2] = 4;
Object[] b = new Object[2];
b[0] = new Object();
b[1] = new Object();

If you want to copy an array, there is a method in the System class which can made it for you:
byte[] a = new byte[2];
byte[] b = new byte[2];
a[0] = 1;
a[1] = 2;
System.arrayCopy(a, 0, b, 0, a.length);

The method System.arrayCopy(...) take the values from a source array to a destination array. You must specifie the initial position where to start reading in the source array, and the initial position where to start writting in the destination array, then the number of elements to copy must be also specified. Both arrays must be intancied before call this method.

The arrays has some properties, and one of them is to know the size of the array, as it was made in the previous example. When you create an array, you do not know how the size will be in the future, so you can use this method when you check the content in a loop. This is very important because if you access to a direction of an array bigger than its size, an exception will be thrown.

No comments:

Post a Comment