1 / 26

Grouping Objects

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.

Download Presentation

Grouping Objects

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Grouping Objects • Arrays and for loops

  2. 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.

  3. 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.

  4. 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(); } ... }

  5. The hourCounts Array

  6. 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]);

  7. 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]);

  8. 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

  9. 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

  10. 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

  11. 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.

  12. 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 }

  13. 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++; }

  14. 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 ( ... ) { ...}

  15. 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]);}

  16. 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!!!

  17.   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;}

  18. 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 !!!

  19.   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];}

  20. 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 ( ... ) { ...}

  21. 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];}

  22. 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); }

  23. 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; }

  24. 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); }

  25. 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; }

  26. 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).

More Related