Chapter 7 Flashcards
1
Q
Arrays & for-each loop
A
for(int value : hourCounts){
System.out.println(“ : “ + value);
}
Arrays can be used with for-each loop but it doesn’t provide access to a loop counter variable thus old for-loop is preferred
2
Q
Which loop should you use?
A
- for-each loop to iterate over all elements in a collection
- for loop when you know how many iterations you will need @ the start of the loop
- while loop when you don’t know how many iterations @ the start of the loop
- If you need to remove elements from a collection whilst examining the whole collection, use a for loop w an iterator - or a while loop if you might want to finish before the end of the collection
3
Q
Conditional operator
A
- choose b/t 2 values
condition? value 1 : value 1
for(int cellValue state){
System.out.print(cellValue == 1 ? ‘+’ : ‘ ‘);
}
System.out.println();
4
Q
lookup tables
A
- HashMap - class allows associations to be created b/t objects in the form of (key, value) pair
- Arrays can implement specialized lookup tables
- We can illustrate the concept of a lookup table via cellular automaton
5
Q
Array initialiser
A
- A list of the values to be stored in a newly-created array
- size does not need to be specified in [] of new int[]
A state table can be set up as follows:
int[] StateTable = new int[]{
0, 1, 0, 0, 1, 0, 0, 1,
};
6
Q
Arrays of more than one dimension
A
- array syntax supports multiple dimensions
- think array of arrays
- declaring an array variable of 1+ dimension:
Cell [] [] cells; - creation of array object
cells = new Cell [numRows] [numCols];
7
Q
Setting up 2D arrays
A
cells = new Cell[numRows][numCols];
for(int row = 0; row < numRows; row++) {
for (int col = 0; col < numCols; col++) {
cells[row][col] = new Cell();
}
}
setupNeighbors();