Presentation is loading. Please wait.

Presentation is loading. Please wait.

Fixed-sized collections

Similar presentations


Presentation on theme: "Fixed-sized collections"— Presentation transcript:

1 Fixed-sized collections
Objects First with Java Fixed-sized collections Introduction to arrays 6.0 © David J. Barnes and Michael Kölling

2 Fixed-size collections
Objects First with Java Fixed-size collections An array is a fixed-size collection type: stores object OR primitive data types more efficient access than dynamic collections Special syntax (like other languages) objects have NO methods but it may have fields The maximum collection size may be pre-determined with an upper limit its size is accessible via a field Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling © David J. Barnes and Michael Kölling 2

3 The weblog-analyzer project
Objects First with Java The weblog-analyzer project Web server records details of each web page access in a log file Supports analysis tasks: Most popular pages Site referencing page Busiest periods How much data is being delivered Broken references Analyze accesses by hour to determine: When to upgrade to more powerful server When to run maintenance at quietest hour © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

4 year month day hour minute
Objects First with Java 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 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 © David J. Barnes and Michael Kölling 4

5 Declaring array variables
Objects First with Java Declaring array variables 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]; Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling © David J. Barnes and Michael Kölling 5

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

7 Creating an array object
Objects First with Java 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 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling © David J. Barnes and Michael Kölling 7

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

9 Accessing an array array[integer expression]
Objects First with Java Accessing an array array[integer expression] Square-bracket notation is used to access an array element by indexing: labels[6] machines[0] people[x 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 © David J. Barnes and Michael Kölling 9

10 Using an array Elements are used like ordinary variables
Objects First with Java 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 © David J. Barnes and Michael Kölling 10

11 Objects First with Java
Standard array use 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 © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

12 declaration, creation and initialization
Objects First with Java Array literals {3, 15, 4, 5, …} declaration, creation and initialization The size is inferred from the data: private int[ ] numbers = { 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 }; XX Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling © David J. Barnes and Michael Kölling 12

13 Objects First with Java
Array length private int[] numbers = { 3, 15, 4, 5 }; int n = numbers.length; not a method call! length is a field rather than a method It is fixed-size and can NOT be changed © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

14 Objects First with Java
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 © David J. Barnes and Michael Kölling 14

15 Arrays and for-each loops
Objects First with Java 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 © David J. Barnes and Michael Kölling 15

16 Objects First with Java
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 © David J. Barnes and Michael Kölling 16

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

18 A Java example for loop version
Objects First with Java A Java example for loop version for(int hour = 0; hour < hourCounts.length; hour++) { System.out.println(hour + ": " + hourCounts[hour]); } while loop version int hour = 0; while(hour < hourCounts.length) { System.out.println(hour + ": " + hourCounts[hour]); hour++; } Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling © David J. Barnes and Michael Kölling 18

19 Array-related methods
System has static arraycopy java.util.Arrays contains static utility methods for processing arrays: copyOf binarySearch fill sort ArrayList has toArray © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

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

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

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

23 Objects First with Java
Practice Fill an array with the first 25 numbers in the Fibonacci sequence: 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]; } Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling © David J. Barnes and Michael Kölling 23

24 for loop with flexibility
Objects First with Java 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 Bigger steps of larger increments © David J. Barnes and Michael Kölling 24

25 for loops and iterators
Objects First with Java 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<Track> it = tracks.iterator(); it.hasNext(); ) { Track track = it.next(); if(track.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) No post-body action required. © David J. Barnes and Michael Kölling 25

26 for PROS CONS 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]

27 Review Arrays: for loops:
Objects First with Java 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 © David J. Barnes and Michael Kölling 27

28 Which loop should I use? for-each: for: while:
Objects First with Java 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 © David J. Barnes and Michael Kölling 28

29 The automaton project An array of cells
Each cell maintains a simple state Usually a small numerical value e.g. on/off or alive/dead The states change according to simple rules Changes affected by neighboring states © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

30 Cell states – blank cells are in state 0
A simple automaton nextState[i] = (state[i-1] + state[i] + state[i+1]) % 2; Step Cell states – blank cells are in state 0 + 1 2 3 4 5 6 © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

31 The conditional operator
Choose between two values: condition ? value1 : value2 for(int cellValue : state) { System.out.print(cellValue == 1 ? '+' : ' '); } System.out.println(); if(cellValue == 1) { return ‘+’; } else { return ‘ ’; © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

32 Further advanced material

33 Arrays of more than one dimension
Array syntax supports multiple dimensions (i.e. 2D array) representing a game board a grid of cells possibly [x, y] coordinates Can be thought of as an array of arrays each x row is an array with y columns © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

34 Objects First with Java
The brain project Cell[][] cells; ... cells = new Cell[numRows][numCols]; for(int row = 0; row < numRows; row++) { for(int col = 0; col < numCols; col++) { cells[row][col] = new Cell(); } © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. © David J. Barnes and Michael Kölling

35 Alternative iteration
for(int row = 0; row < cells.length; row++) { Cell[] nextRow = cells[row]; for(int col = 0; col < nextRow.length; col++) { nextRow[col] = new Cell(); } Array of array style Requires no access to numRows and numCols (accesses using length field) Works with irregular shape arrays, which are supported in Java © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

36 Arrays and Streams java.util.Arrays has several stream() methods that return a Stream based on an array IntStream is a Stream of int values Instream.range() creates a sequential IntStream toArray returns an array from a Stream © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

37 toString() Object class Implicit method call Overriding method
System.out.print() System.out.println() Overriding method Determined at runtime © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.


Download ppt "Fixed-sized collections"

Similar presentations


Ads by Google