Fixed-sized collections

Slides:



Advertisements
Similar presentations
Grouping objects Arrays and for loops. Fixed-size collections Sometimes the maximum collection size can be pre-determined. Programming languages usually.
Advertisements

Arrays.
1 Features of the collection It increases its capacity as necessary. It keeps a private count: –size() accessor. It keeps the objects in order. Details.
Grouping objects Introduction to collections 5.0.
Grouping Objects Arrays and for loops. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Fixed-Size Collections.
Grouping Objects 3 Iterators, collections and the while loop.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Programming with Collections Collections in Java Using Arrays Week 9.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
Grouping objects Collections and iterators. 04/11/2004Lecture 4: Grouping Objects2 Main concepts to be covered Collections Loops Iterators Arrays.
Programming with Collections Grouping & Looping - Collections and Iteration Week 7.
Grouping objects Collections and iterators. Main concepts to be covered Collections Loops Iterators.
REPETITION CITS1001. Scope of this lecture Repetition for loops while loops 2.
Objects First With Java A Practical Introduction Using BlueJ Grouping objects Collections and iterators 2.0.
Grouping objects Arrays, Collections and Iterators 1.0.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Grouping objects Introduction to collections 5.0.
Grouping objects Collections and iterators Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main.
Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.
Scope When we create variables and functions, they are limited in where they are visible and where they can be referenced For the most part, the identifiers.
Grouping objects Iterators. Iterator type Third variation to iterate over a collection Uses a while loop and Iterator object But NO integer index variable.
GROUPING OBJECTS CITS1001. Lecture outline The ArrayList collection Process all items: the for-each loop 2.
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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Grouping objects Introduction to collections 5.0.
1 COS 260 DAY 7 Tony Gauvin. 2 Agenda Questions? 3 rd Mini quiz next class (September 28) –Chap 3 concepts Assignment 1 Corrected Assignment 2 posted.
Grouping objects Iterators, collections and the while loop Equality and Equality == and equals(…)
Fixed-sized collections Introduction to arrays 6.0.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Chapter 7 Arrays…. 7-2 Arrays An array is an ordered list of values An array of size N is indexed from.
Functional Processing of Collections (Advanced) 6.0.
© 2004 Pearson Addison-Wesley. All rights reserved October 5, 2007 Arrays ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
Arrays Chapter 7.
1 © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. for-each PROS easy to use access to ALL items one-by-one ability to change the state.
Chapter VII: Arrays.
for-each PROS CONS easy to use access to ALL items one-by-one
Objects First with Java CITS1001 week 4
Objects First with Java CITS1001
SOFTWARE AND PROGRAMMING 1
Objects First with Java Introduction to collections
Chapter 7 Part 1 Edited by JJ Shepherd
Loop Structures.
Functional Processing of Collections (Advanced)
Chapter-7 part3 Arrays Two-Dimensional Arrays The ArrayList Class.
Objects First with Java CITS1001
Understanding class definitions
COS 260 DAY 9 Tony Gauvin.
Arrays, For loop While loop Do while loop
COS 260 DAY 13 Tony Gauvin.
Java How to Program, Late Objects Version, 10/e
Chapter 8 Slides from GaddisText
COS 260 DAY 10 Tony Gauvin.
Chapter 4: Loops and Files
COS 260 DAY 8 Tony Gauvin.
Object Oriented Programming in java
Objects First with Java Introduction to collections
COS 260 DAY 11 Tony Gauvin.
Collections and iterators
COS 260 DAY 23 Tony Gauvin.
COS 260 DAY 4 Tony Gauvin.
Dr. Sampath Jayarathna Cal Poly Pomona
Arrays October 6, 2006 ComS 207: Programming I (in Java)
Dr. Sampath Jayarathna Cal Poly Pomona
Collections and iterators
Arrays.
Presentation transcript:

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

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

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

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 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 © David J. Barnes and Michael Kölling 4

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

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

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

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

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 + 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 © David J. Barnes and Michael Kölling 9

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

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

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

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

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

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

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

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

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

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.

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

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

Objects First with Java Practice Fill an array with the first 25 numbers in the Fibonacci sequence: 0 1 1 2 3 5 8 13 21 34 ... 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

Objects First with Java Practice Fill an array with the first 25 numbers in the Fibonacci sequence: 0 1 1 2 3 5 8 13 21 34 ... 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

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

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

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]

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

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

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.

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.

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.

Further advanced material

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.

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

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.

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.

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.