260 likes | 358 Views
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.
E N D
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.
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.
Array variable declaration Array object construction Creating an Array Object public class LogAnalyzer { private int[] hourCounts; private LogfileReader reader; public LogAnalyzer() { hourCounts = new int[24]; reader = new LogfileReader(); } ... }
Using an Array Square-brackets notation is used to access an array element - e.g. hourCounts[hour] where hour must be an integer variable holding a valid index to the hourCounts array (0..23). Array elements are used just like variables. They can be assigned: hourCounts[hour] = 42; Or used in expressions: adjusted = 2*(hourCounts[hour] - 3); System.out.println (hourCounts[hour]);
declaration construction use Using an Array private int[] hourCounts; private Person[] students; ... hourCounts = new int[24];students = new Person[100]; ... hourcounts[i] = 0; students[j].enroll ("Co320-S"); System.out.println (hourcounts[i]);
declaration and initialisation Special Syntax for Array Literals private int[] numbers = {3, 15, 4, 5}; ... System.out.println (numbers[i]); Array literals can only be used in initialisations
declaration and initialisation no brackets! Special Syntax for Array Literals private int[] numbers = {3, 15, 4, 5}; ... int n = numbers.length; Array literals can only be used in initialisations Note: ‘length’ is a field of the array object Unlike ‘length()’, which is a method of String
declaration and initialisation no brackets! Special Syntax for Array Literals private int[] numbers = {3, 15, 4, 5}; ... int n = numbers.length; Array literals can only be used in initialisations Note: ‘length’ is a field of the array object Unlike ‘length()’, which is a method of String Unlike ‘size()’, which is a method of ArrayList
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.
Equivalent while-loop form: Statement(s) to be repeated loop header Structure of the for Loop for (initialisation; condition; post-body action) { ... loop body } initialisation; while (condition) { ... loop body ... post-body action }
while loop version for loop version Note: variablehourno longer exists here … Note: variablehourstill exists here … An Example for (int hour = 0; hour < hourCounts.length; hour++) { System.out.println (hour + ": " + hourCounts[hour]); } int hour = 0; while (hour < hourCounts.length) { System.out.println(hour + ": " + hourCounts[hour]); hour++; }
Write this now! 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 ( ... ) { ...}
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[] numbers = {4, 1, 22, 9, 14, 3, 9}; for (int i = 0; i < numbers.length; i++) {System.out.println (numbers[i]);}
Practice Given an array of numbers, print out all the numbers in the array – one number per line. Use a for loop: Actually, arrays also count as collections – so we can use a for-eachloop on them: 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);} simpler!!!
Changescopiesof elements innumbers– does not change any of the elements in numbersitself! Warning !!! Collection (or array) elements accessed through a for-eachloop are copies of the actual elements: for (int n :numbers) {System.out.println (n);} Works But don’t try assigning to them: for (int n :numbers) {n = 2*n;}
But don’t try assigning to them: Changescopiesof elements innumbers– does not change any of the elements in numbersitself! for (int n :numbers) {n = 2*n;} Warning !!!
Changescopiesof elements innumbers– does not change any of the elements in numbersitself! Changesthe elements in numbersitself! Warning !!! But don’t try assigning to them: for (int n :numbers) {n = 2*n;} To do this, we must use a forloop: for (int i = 0; i < numbers.length; i++) {numbers[i] = 2*numbers[i];}
Write this now! Practice Fill an array with the first 100 numbers of theFibonaccisequence. 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 ( ... ) { ...}
Cannot be written with a for-eachloop. Practice Fill an array with the first 100 numbers of theFibonaccisequence. 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 ( ... ) { ...} int[] fib = new int[100]; fib[0] = 0; fib[1] = 1; for (int i = 2; i < fib.length; i++) {fib[i] = fib[i-2] + fib[i-1];}
for loops can haveany size of increment // Print multiples of 3 that are below 40. for (int num = 3;num < 40;num = num + 3) { System.out.println (num); }
Seen before while loop without a collection // Print all even numbers from 0 to 42 inclusive. int index = 0; while (index <= 42) { System.out.println (index); index = index + 2; } int index = 0; while (index >= 42) { System.out.println (index); index = index + 2; } // Programming error? This does nothing at all! // Programming error? This loop never ends! int index = 0; while (index <= 42) { System.out.println (index); index = index - 2; }
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); }
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 findZero (int[] A){for (int i = 0; i < numbers.length; i++) {if (numbers[i] == 0) { return i; }}return -1; }
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).