Objects First with Java CITS1001

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 Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional 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.
Programming with Collections Collections in Java Using Arrays Week 9.
Introduction to Computers and Programming Lecture 15: Arrays Professor: Evan Korth New York University.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
Loops – While, Do, For Repetition Statements Introduction to 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.
Grouping objects Collections and iterators. 04/11/2004Lecture 4: Grouping Objects2 Main concepts to be covered Collections Loops Iterators Arrays.
Chapter 9 Introduction to Arrays
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt * Object-Oriented Software Development Unit.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Grouping objects Introduction to collections 5.0.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
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.
Arrays Arrays in C++ An array is a data structure which allows a collective name to be given to a group of elements which all have.
Arrays An array is a data object that can hold multiple objects, all of the same type. We can think of an array as a storage box which has multiple compartments.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
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.
Arrays Chapter 6. Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define methods that.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
M1G Introduction to Programming 2 2. Creating Classes: Game and Player.
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.
Chapter 8: Understanding Collections Textbook: Chapter 4.
Arrays Chapter 7.
ARRAYS II CITS1001. Scope of this lecture Arrays of objects Multi-dimensional arrays The Game of Life (next lecture) 2.
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Chapter VII: Arrays.
Objects First with Java CITS1001 week 4
EGR 2261 Unit 10 Two-dimensional Arrays
© 2016 Pearson Education, Ltd. All rights reserved.
Fixed-sized collections
GC211Data Structure Lecture2 Sara Alhajjam.
Chapter 7 Part 1 Edited by JJ Shepherd
Loop Structures.
Functional Processing of Collections (Advanced)
Lecture 6 C++ Programming
Objects First with Java CITS1001
Objects First with Java CITS1001
Arrays, For loop While loop Do while loop
7 Arrays.
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
EKT150 : Computer Programming
Java Programming Arrays
Arrays in Java What, why and how Copyright Curt Hill.
COS 260 DAY 8 Tony Gauvin.
Arrays .
String and Lists Dr. José M. Reyes Álamo.
Objects First with Java Introduction to collections
COS 260 DAY 11 Tony Gauvin.
Collections and iterators
Building Java Programs
Arrays in Java.
Suggested self-checks: Section 7.11 #1-11
Collections and iterators
Corresponds with Chapter 5
Java Coding 6 David Davenport Computer Eng. Dept.,
Arrays.
Presentation transcript:

Objects First with Java CITS1001 Arrays CITS1001 © David J. Barnes and Michael Kölling

Scope of this lecture Arrays (fixed size collections) Declaring and constructing arrays Using and returning arrays Aliasing Reading: Chapter 7 of Objects First with Java 6th Edition Chapter 5 in the 5th and earlier Editions

Fixed-size collections Objects First with Java Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Fixed-size collections Sometimes the maximum collection size can be pre-determined. A special fixed-size collection type is available: an array. Unlike the flexible List collections, arrays can store object references or primitive-type values. Arrays use a special syntax. © David J. Barnes and Michael Kölling

The weblog-analyzer project Objects First with Java Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling The weblog-analyzer project Web server records details of each access. Supports analysis tasks: Most popular pages. Busiest periods. How much data is being delivered. Broken references. Analyze accesses by hour. © David J. Barnes and Michael Kölling

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

Objects First with Java Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling The hourCounts array © David J. Barnes and Michael Kölling

Objects First with Java Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Using an array Square-bracket notation is used to access an array element: hourCounts[...] Elements are used like ordinary variables. The target of an assignment: hourCounts[hour] = ...; In an expression: hourCounts[hour]++; adjusted = hourCounts[hour] – 3; © David J. Barnes and Michael Kölling

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

Objects First with Java Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Practice Write a declaration for an array variable vacant that could be used to refer to an array of boolean variables. Write a declaration for an array variable lettercounts that could be used to refer to an array that counts the frequency of letters of the alphabet. Now write a statement to create this array. What is wrong with the following declarations? Correct them. []int counts; boolean[5000] occupied; © David J. Barnes and Michael Kölling

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

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

The for loop (reminder) Objects First with Java Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling The for loop (reminder) There are two variations of the for loop, for-each and for. The for loop is often used to iterate a fixed number of times. Often used with a variable that changes a fixed amount on each iteration. © David J. Barnes and Michael Kölling

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

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

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

for loop with bigger step Objects First with Java Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling for loop with bigger step // Print multiples of 3 that are below 40. for(int num = 3; num < 40; num = num + 3) { System.out.println(num); } © David J. Barnes and Michael Kölling

Practice How many String objects are created by the following declaration? String[] labels = new String[20]; What is wrong with the following array creation? Correct it. double[] prices = new double(50);

Practice Correct all the errors in the following method. /** Print all values in the marks array that are greater than mean. @param marks An array of mark values. @param mean The mean (average) mark. */ public void printGreater(double marks, double mean) { for (index = 0; index <= marks.length(); index++) { if (marks[index] > mean) { System.out.println(marks[index]); }

Challenge A Lab Class has a limit to the number of students who may be enrolled in a particular tutorial group. In view of this, would it be more appropriate to use an fixed-size (eg array) or flexible (eg ArrayList) collection for the students in a particular lab? Give reasons both for and against the alternatives.

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

Objects First with Java More examples Using ARRAYS More examples © David J. Barnes and Michael Kölling

Uses of arrays Arrays are used when we have large numbers of identical objects that we want to operate on as a collection A collection of student marks that we want to analyse A collection of temperatures that we want to average A collection of names that we want to sort e.g. Bureau of Meteorology data ALBANY Max 25.1 25.1 24.1 21.5 18.7 16.6 15.7 15.9 17.4 18.8 20.8 23.4 Min 13.5 14.3 13.3 11.6 9.8 8.1 7.4 7.4 7.9 9.0 10.6 12.3 Rain 28 25 29 66 102 104 126 104 81 80 46 24 PERTH AIRPORT Max 31.4 31.7 29.5 25.2 21.4 18.7 17.6 18.3 20.0 22.3 25.4 28.5 Min 16.7 17.4 15.7 12.7 10.2 9.0 8.0 7.9 8.8 10.1 12.4 14.6 Rain 8 14 15 46 108 175 164 117 68 48 25 12

Declaring arrays An array is declared using similar syntax to any other variable int[] a; Declares a to be a variable representing an array of ints double[] temps; Declares temps to be a variable representing an array of doubles String[] names; Declares names to be a variable representing an array of Strings Student[] marks; Declares marks to be a variable representing an array of Student objects

Creating Arrays I An array is an object in a Java program Therefore the declaration simply creates a reference to “point to” the array, but does not create the array itself Hence the declaration int[] a; creates a space called a, big enough to hold an object reference, and initially set to the special value null Only space for the array reference has been created, not for the array itself a null

Creating Arrays II In order to actually create the array, we must use the keyword new (just like creating any other object) int[] a; a = new int[7]; An object is created that contains seven variables of type int a The expression a.length can be used to refer to the size of a

Creating Arrays III The seven variables do not have individual names They are referred to by the array name, and an index a[0] a[1] a[2] a[3] a[4] a[5] a[6] a

Referencing array elements Array elements can be used in the same ways and in the same contexts as any other variable of that type a[4] = 15; a[2] = 7; a[3] = 2*a[2] – a[4]; a[6] = a[0] + 17; a[0] a[1] a[2] 7 a[3] -1 a[4] 15 a[5] a[6] 17

Indexing arrays A lot of the power of arrays comes from the fact that the index can be a variable or an expression int x = 3; a[x] = 5; a[7-x] = 44; a[0] a[1] a[2] 7 a[3] 5 a[4] 44 a[5] a[6] 17

Summing the integers in an array private int sum(int[] a) { int sum=0; for (int ai : a) { sum = sum + ai; } return sum; Here ai is an element of the array a The for-each loop is the best choice for this problem because we are accessing every element of the array and not removing or adding any elements

Or using a for loop private int sum(int[] a) { int sum = 0; Here i is being used as an index into the array a private int sum(int[] a) { int sum = 0; for (int i = 0; i < a.length; i++) sum = sum + a[i]; } return sum;

Find the biggest integer in an array Note that this is only well-defined for non-empty arrays! Again i is an element of the array a private int max(int[] a) { int max = a[0]; for (int i : a) if (i > max) max = i; } return max;

Or using a for loop private int max(int[] a) { int max = a[0]; Here i is being used as an index into the array a private int max(int[] a) { int max = a[0]; for (int i = 1; i < a.length; i++) if (a[i] > max) max = a[i]; } return max;

Find the index of the biggest integer private int max(int[] a) { int k = 0; for (int i = 1; i < a.length; i++) { if (a[i] > a[k]) { k = i; } return k; A for-each loop will not work for this example. Why not?

Returning an array Suppose we want to find the running sums of a private int[] sums(int[] a) { int[] sums = new int[a.length]; sums[0] = a[0]; for (int i = 1; i < a.length; i++) sums[i] = sums[i–1] + a[i]; } return sums;

Returning an array Suppose we want to average each pair of elements of a avs({2,6,–8,2}) = {4,–3} private int[] avs(int[] a) { int[] avs = new int[a.length / 2]; for (int i = 0; i < a.length-1; i = i+2) avs[i / 2] = (a[i] + a[i+1]) / 2; } return avs;

Updating an array Sometimes instead of creating a new array, we want to update the old one But this method doesn’t return anything… private void sums(int[] a) { for (int i = 1; i < a.length; i++) a[i] = a[i–1] + a[i]; }

Arrays can share memory int[] a, b; a b

Arrays can share memory int[] a, b; a = new int[3]; a b

Arrays can share memory int[] a, b; a = new int[3]; b = a; a b

Arrays can share memory int[] a, b; a = new int[3]; b = a; System.out.println(b[2]); a b

Arrays can share memory int[] a, b; a = new int[3]; b = a; System.out.println(b[2]); a[2] = 9; 9 a b

Arrays can share memory int[] a, b; a = new int[3]; b = a; System.out.println(b[2]); a[2] = 9; 9 9 a b

Aliasing This is called aliasing Basically one array with two names It applies in the same way with any other object-types too Be careful with equality over arrays In some applications we might want to use aliasing deliberately

Changes to parameters are usually lost When we call a method with a parameter of a primitive type, any updates to the parameter are local only The parameter is a new variable private void f(int a) {a = 666;} … int x = 5; System.out.println(x); f(x); 5 x is unchanged

But arrays are persistent When we call a method with a parameter of object type, the parameter is a new variable but it refers to the same space on the heap private void f(int[] a) {a[0] = 666;} … int[] x = {5,3,1}; System.out.println(x[0]); f(x); 5 666 x is unchanged but x[0] is changed

Objects First with Java Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Review Arrays are appropriate where a fixed-size collection is required. Arrays and for-loops go together Methods can return arrays Arrays are reference types: if you pass an array as a parameter and change it within a method, then the change will be visible afterwards. © David J. Barnes and Michael Kölling

Objects First with Java CITS1001 MORE Arrays CITS1001 © David J. Barnes and Michael Kölling

Scope of this lecture Arrays of objects Multi-dimensional arrays The Game of Life (next lecture)

Objects First with Java Arrays of objects The arrays we have seen so far had elements of a primitive type int[], double[], boolean[], etc. But an array can also hold objects e.g. Term[] Arrays can also be two-dimensional e.g. int[][] Arrays can also be three-dimensional, or more But we won’t get to that in CITS1001 © David J. Barnes and Michael Kölling

Objects First with Java Arrays of objects When using an array of primitive type, there are two steps involved Declare the variable to refer to the array Create the space for the array elements using new When using an array of object type, there are three steps involved Populate the array with objects by repeatedly using new, often in a loop © David J. Barnes and Michael Kölling

A Student class public class Student { private String studentNumber; private int mark; public Student(String studentNumber, int mark) { this.studentNumber = studentNumber; this.mark = mark; } public String getStudentNumber() { return studentNumber; public int getMark() { return mark; A skeleton version of a possible Student class in a student records system

Creating a unit list Declare Create Populate Student[] unitList; unitList = new Student[numStudents]; unitList[0] = new Student(“042371X”,64); unitList[1] = new Student(“0499731”,72); unitList[2] = new Student(“0400127”,55); … unitList[numStudents-1] = new Student(“0401332”,85); Declare Create Populate

The three steps unit null unit null null null null null unit[0]

Using arrays of objects Using an array of objects is the same as using any array You just need to remember that the elements are objects! private Student top(Student[] unitlist) { Student top = unitlist[0]; for (Student si : unitlist) if (si.getMark() > top.getMark()) top = si; return top; }

Compare with max private int max(int[] a) { int max = a[0]; for (int i : a) if (i > max) max = i; return max; }

Student top(Student[] unitList) Method signatures int max(int[] a) Student top(Student[] unitList)

Initialisation int max = a[0]; Declare a variable to hold the “best so far”, and initialise it to the first element in the array Student top = unitList[0];

Processing for (int i : a) if (i > max) max = i; Check each element in turn, compare it with the best so far, and update the best if necessary for (Student si : unitList) if (si.getMark() > top.getMark()) top = si;

Return return max; Finally return the extreme element – the highest int or the Student with the best mark return top;

What if we want to find the highest mark? private int highestMark(Student[] unitlist) { int max = unitlist[0].getMark(); for (Student si : unitlist) if (si.getMark() > max) max = si.getMark(); return max; }

Much better to use the existing method! Do not write another looping method! Use the already-written functionality private int highestMark(Student[] unitlist) { return top(unitlist).getMark(); }

Objects First with Java 2D arrays We sometimes need arrays with more than one dimension int[][] a = new int[4][3]; a[0][0] a[0][1] a[0][2] This creates an array with four “rows” and three “columns” The “row” index ranges from 0–3 and the “column” index from 0–2 a[1][0] a[1][1] a[1][2] a[2][0] a[2][1] a[2][2] a[3][0] a[3][1] a[3][2] © David J. Barnes and Michael Kölling

2D arrays contd. This is really an array where each element is itself an array a is a valid variable, representing the whole thing a[0] is a valid variable, representing the first “row” a[0][2] is a valid variable, representing the last element in the first “row”

2D arrays contd. a a[0] a[1] a[2] a[3] a[0][0] a[0][1] a[0][2] a[1][0] a[0][1] a[0][2] a[0] a[1][0] a[1][1] a[1][2] a[1] a a[2][0] a[2][1] a[2][2] a[2] a[3][0] a[3][1] a[3][2] a[3]

2D arrays contd. Given that an array is an object, this is really just a special case of an array of objects The single statement int[][] a = new int[4][3]; declares the array variable a, and both creates and populates the array!

2D arrays examples A 2D array is normally processed with two nested for-loops private int sum(int[][] a) { int sum = 0; for (int i = 0; i < a.length; i++) for (int j = 0; j < a[i].length; j++) sum = sum + a[i][j]; return sum; }

2D arrays examples Suppose we want to return the index of the first row containing any element that is true private int firsttrue(boolean[][] a) { for (int i = 0; i < a.length; i++) for (int j = 0; j < a[i].length; j++) if (a[i][j]) return i; return -1; }

2D arrays example We will illustrate the use of 2D arrays further with a case study of The Game of Life http://en.wikipedia.org/wiki/Conway’s_Game_of_Life In the next lecture… And there’s plenty of practice in the lab too