Fixed-sized collections

Fixed-sized collections

Fixed-sized collections Introduction to arrays 6.0 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 2

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling 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: Most popular pages When to upgrade to more powerful 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

server 3 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 - 4 Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling

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 5

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

} ... } Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling 6 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 Klling 7 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 Klling 8 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 Klling 9 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 Klling

10 Standard array use private int[] hourCounts; private String[] names; declaration ... hourCounts = new int[24]; names = new String[10]; creation ... hourcounts[i] = 0; hourcounts[i]++; System.out.println(hourcounts[i]); 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

use 11 Array literals {3, 15, 4, 5, } The size is inferred from the declaration, creation and data: initialization private int[ ] numbers = { 3, 15, 4, 5 }; Array literals in this form can only be used in declarations and NOT like this:

XX 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 Klling 12 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. 13 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]++; Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Klling 14 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 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 Klling 16 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 Klling

17 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 Klling 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. 19 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 Klling 20 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 Klling

21 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 Klling 22 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 Klling 23 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); 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 track = it.next(); if(track.getArtist().equals(artist)) { it.remove(); } } No post-body action required. 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

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 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 Klling 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 Non-collections: condition(s) use a for or while loop Removing elements:

(if examining ALL elements) use for with Iterator (if stopping before the collection ends) use28 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. 29

A simple automaton nextState[i] = (state[i-1] + state[i] + state[i+1]) % 2; Ste p Cell states blank cells are in state 0 0 + 1 + 2 3

+ 4 6 + + + + + + +

+ + + + + 5 + + + +

+ + + + + 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. + + + + + 30

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

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. 33 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. 34 Alternative iteration for(int row = 0; row Cell[] nextRow = for(int col = 0; nextRow[col] }

} < cells.length; row++) { cells[row]; col < nextRow.length; col++) { = new Cell(); Array of array style Requires no access to numRows and numCols (accesses using length field) Works with irregular shape arrays, 35 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. 36 toString() Object class Implicit method call System.out.print() System.out.println() Overriding method Determined at

runtime 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. 37

Recently Viewed Presentations

  • Seamus heany

    Seamus heany

    Autobiographical poem about family tradition and admiration for elders. ... She is still under public scrutiny. Possibly referring to honeycomb structure. Time shift links to modern Ireland. Portion of amnion (embryous membrane) or a close-fitting cap worn by women.
  • CS267: Introduction

    CS267: Introduction

    Would complicate bookkeeping of algorithm Dragonfly network on Edison uses randomization to deal with shared network This algorithm assume homogeneous, unshared machines Less copy overhead on arrival Today's network: unpacked slabs seem best * * For reproducible science (although some...
  • Topic Ontologies - University at Buffalo

    Topic Ontologies - University at Buffalo

    Inverted index Linked lists generally preferred to arrays Dynamic space allocation Insertion of terms into documents easy Space overhead of pointers Inverted index construction Applications of IR Specialized Domains biomedical, legal, patents, intelligence Summarization Cross-lingual Retrieval, Information Access Question-Answering Systems...
  • Aug 2011 CAP Safety Meeting Lt Col Larry

    Aug 2011 CAP Safety Meeting Lt Col Larry

    www.FAASafety.gov. and look for Course ALC-34, Maneuvering: Approach and Landing. The Do's of Maneuvering Flight • Do remember that the majority of fatal stall/spin accidents occur at low altitudes, because the closer you are to the ground the less time...
  • ALERT Three-Level Strategic Approach Level 3: Grand Challenges

    ALERT Three-Level Strategic Approach Level 3: Grand Challenges

    plosives Detection Sensor Suite Proof-of-Principle Tests of Research F3: Explosives Detection Sensor Systems F1: Explosives Characterization Level 1 Fundamental Science F2: Explosives Detection Sensors F4: Blast Mitigation Research Barriers * *
  • Gregor Mendel - Knaust

    Gregor Mendel - Knaust

    Gregor Mendel Karl-Lutz De Regules Jessica Gonzalez Jose Salas Alex Villamar "The Father of Genetics" Table of Contents Timeline 1822 born July 20 in Heizendorf, Austria 1833 is enrolled in Piarist secondary school in Leipnik, Heinzendof 1838 at the age...
  • You: The most important piece of the bulk

    You: The most important piece of the bulk

    In which state of stress are you most likely to make a mistake in an emergency? Hypostress. ... If you're operating a substation remotely and flip the wrong breaker because you were on "autopilot" (very familiar with this substation), what...
  • WRF Tutorial For Version 2.2 / Synoptic Lab

    WRF Tutorial For Version 2.2 / Synoptic Lab

    Arial MS Pゴシック Arial Times Arial Courier Wingdings Blank Presentation WRF Tutorial Background on WRF model WRF advantages Further advantages WRF disadvantages WRF and related software Web resources My resources Setup on "hurricane" machines Environment setup > …is the command...