Presentation is loading. Please wait.

Presentation is loading. Please wait.

Grouping objects Arrays. 2 Fixed-size collections The maximum collection size may be pre-determined with an upper limit Array is an fixed-size collection.

Similar presentations


Presentation on theme: "Grouping objects Arrays. 2 Fixed-size collections The maximum collection size may be pre-determined with an upper limit Array is an fixed-size collection."— Presentation transcript:

1 Grouping objects Arrays

2 2 Fixed-size collections The maximum collection size may be pre-determined with an upper limit Array is an fixed-size collection type: –stores object OR primitive data types –special syntax unlike usual Java method calls (uses same as other languages) –more efficient access than flexible-sized collections Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

3 3 The weblog-analyzer project Web server records details of each web page access in a log file Supports the following analysis tasks: –Most popular pages –Site that referenced the page –Busiest periods over day/week/month –How much data is being delivered –Broken references at other sites Analyze accesses by hour to determine: –when to upgrade to more powerful server –when to run maintenance (quietest period)

4 4 weblog-analyzer Our server writes to a text log file named: weblog.txt Web server will record a time stamp of June 7, 2011 at 3:45am in the format: year month day hour minute 2011 06 07 03 45 Current analyzer is limited to providing a count for the number of accesses in each 1 hour period over the duration covered by the log (0 - 23) Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

5 5 Declaring array variables Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling LogAnalyzer class contains the field: private int[] hourCounts; — indicates hourCounts is of type integer array int would be the base type of the array — the array object would store type int values difference between declarations int hourCounts; // single int variable int[] hourCounts; // int-array variable hourCounts = new int[24];

6 6 Creating an array object Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling public class LogAnalyzer { private int[] hourCounts; private LogfileReader reader; public LogAnalyzer() { hourCounts = new int[24]; reader = new LogfileReader(); }... } Array object creation — specifies size Array variable declaration — does not contain size

7 7 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Creating an array object new type[integer-expression] new int[24] creates an object of type integer array creates array capacity to hold 24 integers

8 8 The hourCounts array Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling private int[] hourCounts; new int[24]; = hourCounts = new int[24];

9 9 Accessing an array array[integer expression] Square-bracket notation is used to access an array element by indexing: labels[6] machines[0] people[x + 10 -y] Valid indices depend on the length of the array and range from [0 … (length-1)] Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

10 10 Using an array Elements are used like ordinary variables The target of an assignment: labels[5] =... ; machines[index] = new Machine(10); In an expression: double half = readings[0] / 2; adjusted = hourCounts[hour] – 3; hourCounts[hour]++; System.out.print(item[1].getName()); Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

11 11 Standard array use Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling private int[] hourCounts; private String[] names;... hourCounts = new int[24]; names = new String[10];... hourcounts[i] = 0; hourcounts[i]++; System.out.println(hourcounts[i]); declaration creation use

12 12 Array literals {3, 15, 4, 5, …} Array literals in this form can only be used in declarations and NOT like this: numbers = { 3, 15, 4, 5 }; Related uses require new : numbers = new int[ ] { 3, 15, 4, 5 }; Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling private int[ ] numbers = { 3, 15, 4, 5 }; declaration, creation and initialization The size is inferred from the data: XX

13 13 Array length length is a field rather than a method It is fixed size and can not be changed Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling private int[] numbers = { 3, 15, 4, 5 }; int n = numbers.length; NO brackets! NO parentheses!

14 14 LogAnalyzer example The hourCounts field is necessary to store the analysis of the access data hourCounts = new int[24]; The constructor creates an array object of 24 integers for the hourCounts field hourCounts.length // equals 24 Each of the 24 integer elements represent the number of accesses made within that particular hour (in a 24-hour day) hourCounts[hour]++; A larger integer value = more accesses Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

15 15 The for loop The two variations of the for loop (use definite iteration): > for-each > for The for loop is often used: –to iterate a fixed number of times –with a variable that changes a fixed amount on each iteration The for loop is similar to while loop Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

16 16 for loop pseudo-code Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling for(initialization; condition; post-body action) { statements to be repeated } General form of the for loop Equivalent in while-loop form initialization; while(condition) { statements to be repeated post-body action }

17 17 A Java example Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 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++; } for loop version while loop version

18 18 Practice Given an array of numbers, print out all the numbers in the array using a for loop: Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling int[] numbers = { 4, 1, 22, 9, 14, 3, 9}; for...

19 19 Practice Given an array of numbers, print out all the numbers in the array using a for loop: Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling int[] numbers = { 4, 1, 22, 9, 14, 3, 9}; for(int num = 0; num < numbers.length; num++) { System.out.println(numbers[num]); }

20 20 Practice Fill an array with the first 25 numbers in the Fibonacci sequence: Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling int[] fib = new int[25]; fib[0] = 0; fib[1] = 1; for... 0 1 1 2 3 5 8 13 21 34...

21 21 Practice Fill an array with the first 25 numbers in the Fibonacci sequence: Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling int[] fib = new int[25]; fib[0] = 0; fib[1] = 1; for(int num = 2; num < fib.length; num++) { fib[num] = fib[num - 1] + fib[num -2]; } 0 1 1 2 3 5 8 13 21 34...

22 22 for loop with flexibility Print multiples of 3 that are below 40 Start at any element for(int num = 3; num < 40; num = num + 3) { System.out.println(num); } End at any element for(int num = 3; num < 40; num = num + 3) { System.out.println(num); } Bigger steps of larger increments for(int num = 3; num < 40; num = num + 3) { System.out.println(num); }

23 23 Arrays and for-each loops Can we use for-each to access EVERY element in the array collection without adding/removing any elements? YES for-each loops may be used on arrays: for(int value : hourCounts) { System.out.println(value); } However, there is NO index counter to use if location of element is needed

24 24 for loops and iterators Can we use a for loop with an Iterator to access every element in a collection and remove selective elements? YES A special use of for loop may be used: for(Iterator it = tracks.iterator(); it.hasNext(); ) { Track t = it.next(); if(t.getArtist().equals(artist)) { it.remove(); } There is NO post-body action in the loop header, because the increment is being taken care of by it.next in the loop body (But, the semicolon is still necessary)

25 25 for PROS may be used on a collection, non-collection or array flexibility on start/end item and increment amount ability to add/remove/change the item during the loop access to loop counter (variable) is provided increment is completed automatically after each iteration may even be used with Iterators CONS definite iteration so number of elements MUST be known access to items in sequence [start to end]

26 26 Review Arrays: –are appropriate where a fixed-size collection is required –use a special syntax (no methods) for loops: –are used when an index variable is required –offer an alternative to while loops when the number of repetitions is known –Used with a regular step size Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

27 27 Which loop should I use? for-each: –iterate over ALL elements in a collection –no adding or removing of any elements –no loop counter (index) is needed for: –definite iteration with known start and end –increment amount may be flexible (> 1) –loop counter (index) is needed while: –indefinite iteration with unknown # of iterations –loop end can be determined by some condition(s)  Non-collections: use a for or while loop  Removing elements: (if examining ALL elements ) use for with Iterator (if stopping before the collection ends) use while

28 28 Lambda expressions Syntax defined as: Parameters -> Body Introduced in Java 8 Allows function of a local-anonymous method to be written exactly where it is being used - esp. useful if short and only being used once Same as a method call with passed parameters and/or potential return value (or void) - but saves time/effort of coding another method Could easily be used with the forEach method of Iterable objects such as an ArrayList as a passed parameter - replaces using a for-each loop for a collection Arrow token

29 29 for-each loop vs. forEach() Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Equivalent using ArrayList.forEach() students.forEach(name -> System.out.println(name)); ArrayList students = new ArrayList (); Printing a collection using a for-each loop for(String name : students ) { System.out.println(name); }


Download ppt "Grouping objects Arrays. 2 Fixed-size collections The maximum collection size may be pre-determined with an upper limit Array is an fixed-size collection."

Similar presentations


Ads by Google