Grouping Objects Arrays and for loops FixedSize Collections
Grouping Objects Arrays and for loops
Fixed-Size Collections • Sometimes the maximum collection size is known. • Programming languages usually offer a special fixed-size collection type: the array. • Java arrays can store objects or primitive values. • Arrays use a special syntax. Objects First with Java - A Practical Introduction using Blue. J, © David J. Barnes, Michael Kölling
The weblog-analyzer Project • A web server records details of each access. • It supports webmaster tasks: • • Most popular pages Busiest periods How much data is being delivered Broken references • It analyses accesses by hour. Objects First with Java - A Practical Introduction using Blue. J, © David J. Barnes, Michael Kölling
Creating an Array Object public class Log. Analyzer { private int[] hour. Counts; Array variable declaration private Logfile. Reader reader; Array object construction public Log. Analyzer() { hour. Counts = new int[24]; reader = new Logfile. Reader(); } . . . } Objects First with Java - A Practical Introduction using Blue. J, © David J. Barnes, Michael Kölling
The hour. Counts Array Objects First with Java - A Practical Introduction using Blue. J, © David J. Barnes, Michael Kölling
Using an Array Square-brackets notation is used to access an array element - e. g. hour. Counts[hour] where hour must be an integer variable holding a valid index to the hour. Counts array (0. . 23). Array elements are used just like variables. They can be assigned: hour. Counts[hour] = 42; Or used in expressions: adjusted = 2*(hour. Counts[hour] - 3); System. out. println (hour. Counts[hour]); Objects First with Java - A Practical Introduction using Blue. J, © David J. Barnes, Michael Kölling
Using an Array private int[] hour. Counts; private Person[] students; . . . hour. Counts = new int[24]; students = new Person[100]; declaration construction . . . hourcounts[i] = 0; students[j]. enroll ("Co 320 -S"); System. out. println (hourcounts[i]); use Objects First with Java - A Practical Introduction using Blue. J, © David J. Barnes, Michael Kölling
Special Syntax for Array Literals declaration and initialisation private int[] numbers = {3, 15, 4, 5}; . . . System. out. println (numbers[i]); Array literals can only be used in initialisations Objects First with Java - A Practical Introduction using Blue. J, © David J. Barnes, Michael Kölling
Special Syntax for Array Literals declaration and initialisation private int[] numbers = {3, 15, 4, 5}; . . . no brackets! int n = numbers. length; Note: literals ‘length a field of the array object Array can’ is only be used in initialisations Unlike ‘length()’, which is a method of String Objects First with Java - A Practical Introduction using Blue. J, © David J. Barnes, Michael Kölling
Special Syntax for Array Literals declaration and initialisation private int[] numbers = {3, 15, 4, 5}; . . . no brackets! int n = numbers. length; Note: literals ‘length a field of the array object Array can’ is only be used in initialisations Unlike‘‘size() length() ’, which is aismethod a method of Array. List of String Objects First with Java - A Practical Introduction using Blue. J, © David J. Barnes, Michael Kölling
The for Loop • There are two variations of the for loop, for-each (already seen) and for. • The for loop is often used to iterate a fixed number of times. • It is usually used with a control variable that changes a fixed amount on each iteration. Objects First with Java - A Practical Introduction using Blue. J, © David J. Barnes, Michael Kölling
Structure of the for Loop loop header for (initialisation; condition; post-body action) { . . . loop body } Statement(s) to be repeated Equivalent while-loop form: initialisation; while (condition) { . . . loop body . . . post-body action } Objects First with Java - A Practical Introduction using Blue. J, © David J. Barnes, Michael Kölling
An Example for loop version for (int hour = 0; hour < hour. Counts. length; hour++) { System. out. println (hour + ": " + hour. Counts[hour]); } Note: variable hour no longer exists here … while loop version int hour = 0; while (hour < hour. Counts. length) { System. out. println(hour + ": " + hour. Counts[hour]); hour++; } Note: variable hour still exists here … Objects First with Java - A Practical Introduction using Blue. J, © David J. Barnes, Michael Kölling
Practice Given an array of numbers, print out all the numbers in the array – one number per line. Use a for loop: int[] numbers = {4, 1, 22, 9, 14, 3, 9}; for (. . . ) { . . . } Write this now! Objects First with Java - A Practical Introduction using Blue. J, © David J. Barnes, Michael Kölling
Practice Given an array of numbers, print out all the numbers in the array – one number per line. Use a for loop: int[] numbers = {4, 1, 22, 9, 14, 3, 9}; for (int i = 0; i < numbers. length; i++) { for (. . . ) { . . . System. out. println (numbers[i]); } Objects First with Java - A Practical Introduction using Blue. J, © David J. Barnes, Michael Kölling
Practice Actually, Given an arraysofalso numbers, count as print collections out all the – so numbers we in the can usearray a for-each – one number loop onper them: line. Use a for loop: int[] numbers = {4, 1, 22, 9, 14, 3, 9}; for (int i = 0; i < numbers. length; i++) { System. out. println (numbers[i]); } for (int n : numbers) { System. out. println (n); } sim ple r!! ! Objects First with Java - A Practical Introduction using Blue. J, © David J. Barnes, Michael Kölling
Warning !!! Collection (or array) elements accessed through a for -each loop are copies of the actual elements: for (int n : numbers) { System. out. println (n); } W or ks But don’t try assigning to them: for (int n : numbers) { n = 2*n; } Changes copies of elements in numbers – does not change any of the elements in numbers itself! Objects First with Java - A Practical Introduction using Blue. J, © David J. Barnes, Michael Kölling
Warning !!! But don’t try assigning to them: for (int n : numbers) { n = 2*n; } Changes copies of elements in numbers – does not change any of the elements in numbers itself! Objects First with Java - A Practical Introduction using Blue. J, © David J. Barnes, Michael Kölling
Warning !!! But don’t try assigning to them: for (int n : numbers) { n = 2*n; } Changes copies of elements in numbers – does not change any of the elements in numbers itself! To do this, we must use a for loop: for (int i = 0; i < numbers. length; i++) { numbers[i] = 2*numbers[i]; } Changes the elements in numbers itself! Objects First with Java - A Practical Introduction using Blue. J, © David J. Barnes, Michael Kölling
Practice Fill an array with the first 100 numbers of the Fibonacci sequence. Fibonacci: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, . . . (each number is the sum of the previous two numbers) (start with zero and one) int[] fib = new int[100]; fib[0] = 0; fib[1] = 1; for (. . . ) { . . . } Write this now! Objects First with Java - A Practical Introduction using Blue. J, © David J. Barnes, Michael Kölling
Practice Fill an array with the first 100 numbers of the Fibonacci sequence. Fibonacci: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, . . . (each number is the sum of the previous two numbers) (start with zero and one) int[] fib = new int[100]; fib[0] = 0; fib[1] = 1; Cannot be written with a for-each loop. for (int i = 2; i < fib. length; i++) { for (. . . ) { . . . fib[i] = fib[i-2] + fib[i-1]; } Objects First with Java - A Practical Introduction using Blue. J, © David J. Barnes, Michael Kölling
for loops can have any size of increment // Print multiples of 3 that are below 40. for (int num = 3; num < 40; num = num + 3) { System. out. println (num); } Objects First with Java - A Practical Introduction using Blue. J, © David J. Barnes, Michael Kölling
while loop without a collection // Print all even numbers from 0 to 42 inclusive. int index = 0; while (index <= 42) { Se System. out. println (index); en b e index = index + 2; for e } // Programming error? This does nothing at all! int index = 0; while (index >= 42) { System. out. println (index); index = index + 2; } // Programming error? This loop never ends! int index = 0; while (index <= 42) { System. out. println (index); index = index - 2; } Objects First with Java - A Practical Introduction using Blue. J, © David J. Barnes, Michael Kölling
The same – but with for loops // Print all even numbers from 0 to 42 inclusive. for (int index = 0; index <= 42; index = index + 2) { System. out. println (index); } // Programming error? This does nothing at all! for (int index = 0; index >= 42; index = index + 2) { System. out. println (index); } // Programming error? This loop never ends! for (int index = 0; index <= 42; index = index - 2) { System. out. println (index); } Objects First with Java - A Practical Introduction using Blue. J, © David J. Barnes, Michael Kölling
for loops can exit early /** * Search an array for a zero. * * @return The index of the first zero element * (if none found, return -1) */ public int find. Zero (int[] A) { for (int i = 0; i < numbers. length; i++) { if (numbers[i] == 0) { return i; } } return -1; } Objects First with Java - A Practical Introduction using Blue. J, © David J. Barnes, Michael Kölling
Review • Arrays are appropriate where a fixed-size collection is required. • Arrays use special [square brackets] syntax. • For loops are a better alternative to while loops when the number of repetitions is known. • For loops are often used to introduce and control an index variable when iterating through arrays. • For loops can exit early (with a return). Objects First with Java - A Practical Introduction using Blue. J, © David J. Barnes, Michael Kölling
- Slides: 26