An array is multiple storage locations under one name. For now
we will talk about one and two dimensional arrays.
All the primitive data types that we have learned and used concerning
regular variables also apply to arrays.
int num = new int; // declare / initialize an integer variable
int nums[] = new int [10]; // declare and allocate space for 10 integer
// numbers. The 10 elements have the same
// name but each one will be referred to
// with a different subscript or position
// in the array. Thos array contains 10
// integer locations, number 0 thru 9
Anything that you can do with an integer variable, you can do with
each element of an integer array. But you must indicate which element
you are referring to.
e.g.. nums[0]=100;
nums[5]=200; etc.
JOptionPane.showMessageDialog(null,"answer is "+nums[2]);
Loops make working with arrays very easy.
for example:
int tot=100;
int n=0;
do
{
nums[n] = tot;
n=n+1;
} while (n <= 9 );
Remember that all rules that apply to variables of a specific type
also apply to each element of an array of that type.
Two dimensional arrays adhere to all the rules noted above, except
any reference to a two dimensional array must have 2 subscripts.
int numbers[] [] = new int [5] [10];
The above array has 5 rows and 10 columns.
The rows are numbered 0 thru 4, and the columns are numbered 0 thru 9.
Any reference to the array will have 2 subscripts and the first one will be
the row and the second one will be the column.
e.g.. numbers[1][3] = 100;
Loops are very useful with two dimensional arrays just like one
dimensional arrays, but a lot of the times nested loops are used
because of the nature of two dimensional arrays.
e.g.. int tot=10;
for(int a=0;a<=4;a++)
{
for(int b=0;b<=9;b++)
{
numbers[a][b] = tot;
tot=tot+10;
}
}
.
arrays can be declared but still need to be explicitly initialized
int [] dataPoints; // declares the array of integer
dataPoints = new int[10] ; // allocates array size (now usable)
dataPoints = new int[numPoints]; // allocates array size with size specified by a run-time variable
an array can be re-initialized (with the same data type) at runtime, at which point old array entries are discarded
Java standard arrays cannot are not dynamically resizable like arrays in Visual Basic or PowerBuilder (i.e. where the language can dynamically extend the array, if needed). Java throws an exception if an out-of-bounds array index is referenced. Java.util's Vector class provides dynamic array-like capability (a Vector can store a collection of any type of object). The standard Vector class does not, however, limit data to a specific data type (data type limitation capability has to be built in a Vector extension).
No comments:
Post a Comment