Think of arrays as a list of variables or objects.
Here are some examples of constructing an array:
int[] n = new int[3];
double[] d = new double[5];
String[] str = new String[8];
You can also create arrays of objects, like this:
Car[] cars = new Car[50];
The number in the brackets is the length of the array, or how many elements are in the array. This is fixed. The length of the array is the same for the entire program. You can get the array length using .length. Using the above examples, n.length is 3, d.length is 5, and str.length is 8. Note: .length is an instance field, not a method, so don't use parentheses.
An array can only store a certain type of variables. Using the examples above, n can only store int variables, d can only store double variables, str can only store strings, and cars can only store car objects.
To access an element of an array, use [], and place the position inside the brackets (remember position starts counting from 0. So the third car of cars would be cars[2].
For loops are used with arrays a lot, because you can use them to go through each element of an array. For example:
double sum = 0;
for(int i=0; i<d.length; i++){
double x = d[i];
sum += x;
double x = d[i];
sum += x;
// rest of the loop
}
}
We also use for-each loops for arrays. A for each loop does the same thing as the above for loop. It accesses each element in an array from beginning to end.
double sum = 0;
for(double x: d){
for(double x: d){
// for each iteration, the element is assigned to x
sum += x;
// rest of the loop
}
// rest of the loop
}
The for each loop is cool, but you can only use it when you just want to access the elements in an array. Sometimes, you can't use a for each loop and you need to use a regular for loop if you want to, say, change the elements in an array, or if you need to use the position i in the body of the loop, or if you want to access multiple elements of the array at a time.
A two-dimensional array is an array of arrays. For example:
double[][] arr = new double[3][5];
double[][] arr = new double[3][5];
arr is an array of 3 double arrays, and each of those 3 arrays has 5 doubles. This is a matrix. The number in the first bracket is the number of rows, and the number in the second bracket is the number of columns.
arr.length tells us the number of rows. So how do we get the number of columns? Just get the number of columns of one of the rows: arr[0].length. You can use any position, but 0 is simple.
To access an element of a 2-dimensional array, use [i][j]. i is the row of the element, j is the column of the element.
We use nested for loops for 2-dimensional arrays:
for(int i=0; i<arr.length; i++){
for(int i=0; i<arr.length; i++){
for(int j=0; j<arr[0].length; j++){
//body of loop
}
}
No comments:
Post a Comment