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.

Slides:



Advertisements
Similar presentations
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
Advertisements

Grouping objects Iterators. Iterator and iterator() Collections have an iterator() method. This returns an Iterator object. Iterator has three methods:
Grouping objects Arrays and for loops. Fixed-size collections Sometimes the maximum collection size can be pre-determined. Programming languages usually.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
Grouping Objects 3 Iterators, collections and the while loop.
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.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
Grouping Objects 2 Collections and the for-each loop Collections and the while loop.
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.
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
CS0007: Introduction to Computer Programming Introduction to Arrays.
Grouping objects Collections and iterators. Main concepts to be covered Collections Loops Iterators.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
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.
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.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Objects First With Java A Practical Introduction Using BlueJ Supplementary Material for Java
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
Grouping objects Iterators. Iterator type Third variation to iterate over a collection Uses a while loop and Iterator object But NO integer index variable.
Final Review. From ArrayLists to Arrays The ArrayList : used to organize a list of objects –It is a class in the Java API –the ArrayList class uses an.
Objects First With Java A Practical Introduction Using BlueJ Grouping objects Collections and iterators 1.0.
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.
GROUPING OBJECTS CITS1001. Lecture outline The ArrayList collection Process all items: the for-each loop 2.
CSE 1201 Object Oriented Programming ArrayList 1.
COMPUTER PROGRAMMING 2 ArrayLists. Objective/Essential Standard Essential Standard 3.00Apply Advanced Properties of Arrays Essential Indicator 3.02 Apply.
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.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
1 COS 260 DAY 9 Tony Gauvin. 2 Agenda Questions? 3 rd Mini quiz –Good results ->All A’s –Threw out question on name overloading 4 th Mini quiz next class.
Collections and Iteration Week 13.  Collections  ArrayList objects  Using loops with collections Collections and Iteration CONCEPTS COVERED THIS WEEK.
Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.
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.
© 2004 Pearson Addison-Wesley. All rights reserved October 5, 2007 Arrays ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
Chapter 8: Understanding Collections Textbook: Chapter 4.
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
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
Fixed-sized collections
Loop Structures.
Functional Processing of Collections (Advanced)
COS 260 DAY 13 Tony Gauvin.
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
Collections and iterators
Arrays.
Presentation transcript:

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

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

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

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

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 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 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 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 Kölling

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