Scope of this lecture

Similar documents
Grouping objects. Main concepts to be covered

Grouping objects. The requirement to group objects

Grouping Objects. Primitive Arrays and Iteration. Produced by: Dr. Siobhán Drohan. Department of Computing and Mathematics

Scope of this lecture. Repetition For loops While loops

CITS1001 week 4 Grouping objects

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

UNDERSTANDING CLASS DEFINITIONS CITS1001

1B1b Classes in Java Part I

1B1a Arrays. Arrays. Indexing. Naming arrays. Why? Using indexing. 1B1a Lecture Slides. Copyright 2003, Graham Roberts 1

Ticket Machine Project(s)

School of Computer Science CPS109 Course Notes Set 7 Alexander Ferworn Updated Fall 15 CPS109 Course Notes 7

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Object Oriented Design: Identifying Objects

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

Introduction to Programming Using Java (98-388)

1 class Lecture5 { 2 3 "Arrays" 4. Zheng-Liang Lu Java Programming 136 / 174

OBJECT INTERACTION. CITS1001 week 3

Understanding class definitions. Looking inside classes (based on lecture slides by Barnes and Kölling)

C++ for Java Programmers

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

CITS1001 week 4 Grouping objects lecture 2

Object Oriented Programming. Java-Lecture 6 - Arrays

Cloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example,

Lecture 5: Methods CS2301

Instructor: Eng.Omar Al-Nahal

public class TicketMachine Inner part omitted. public class ClassName Fields Constructors Methods

THE UNIVERSITY OF WESTERN AUSTRALIA. School of Computer Science & Software Engineering CITS1001 OBJECT-ORIENTED PROGRAMMING AND SOFTWARE ENGINEERING

Arrays. Eng. Mohammed Abdualal

1st Semester Examinations CITS1001 3

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

Arrays. Inf1-OP. Arrays. Many Variables of the Same Type. Arrays 1. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017

Inf1-OP. Arrays 1. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. February 26, School of Informatics

VARIABLES AND TYPES CITS1001

Computer Science is...

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Arrays and ArrayLists. David Greenstein Monta Vista High School

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 10 INTRODUCTION TO ARRAYS

CT 229 Arrays Continued

CPS122 Lecture: From Python to Java

Unit 14. Passing Arrays & C++ Strings

Cloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example,

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Sorting. Bubble Sort. Selection Sort

Arrays: Higher Dimensional Arrays. CS0007: Introduction to Computer Programming

Inf1-OP. Inf1-OP Exam Review. Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein. March 20, School of Informatics

Last Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it

TOPICS TO COVER:-- Array declaration and use.

Computer Science & Engineering 150A Problem Solving Using Computers

Computer Science II (20082) Week 1: Review and Inheritance

Creating Two-dimensional Arrays

Inf1-OOP. OOP Exam Review. Perdita Stevens, adapting earlier version by Ewan Klein. March 16, School of Informatics

News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.!

Lab: PiggyBank. Defining objects & classes

OBJECT INTERACTION CITS1001

CS121/IS223. Object Reference Variables. Dr Olly Gotel

CS61B Lecture #6: Arrays

Inf1-OP. Arrays 1. Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein. January 30, School of Informatics

Administration. Objects and Arrays. Objects. Agenda. What is an Object? What is a Class?

COS 126 General Computer Science Spring Written Exam 1

Loops and Expression Types

New Concepts. Lab 7 Using Arrays, an Introduction

Arrays. Outline 1/7/2011. Arrays. Arrays are objects that help us organize large amounts of information. Chapter 7 focuses on:

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

AP Computer Science Lists The Array type

ECE 122. Engineering Problem Solving with Java

COMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

Chapter 9 Introduction to Arrays. Fundamentals of Java

OCA Java SE 7 Programmer I Certification Guide By Mela Gupta. Arrays

Tutorial 4. Values and References. Add One A. Add One B. Add One C

FOR Loop. FOR Loop has three parts:initialization,condition,increment. Syntax. for(initialization;condition;increment){ body;

High Institute of Computer Science & Information Technology Term : 1 st. El-Shorouk Academy Acad. Year : 2013 / Year : 2 nd

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

CPSC 427a: Object-Oriented Programming

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal

Array. Prepared By - Rifat Shahriyar

Before we start - Announcements: There will be a LAB TONIGHT from 5:30 6:30 in CAMP 172. In compensation, no class on Friday, Jan. 31.

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal

Classwork 7: Craps. N. Duong & R. Rodriguez, Java Crash Course January 6, 2015

CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II

Object-Oriented Programming in Java

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

CS 231 Data Structures and Algorithms, Fall 2016

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

CONTENTS: Arrays Strings. COMP-202 Unit 5: Loops in Practice

Advanced Computer Programming

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

Object-oriented Programming and Software Engineering CITS1001. Multiple-choice Mid-semester Test

More sophisticated behaviour

The action of the program depends on the input We can create this program using an if statement

User Defined Functions

CMPS 12A Winter 2006 Prof. Scott A. Brandt Final Exam, March 21, Name:

Computer Programming: C++

CS 61B Data Structures and Programming Methodology. July 2, 2008 David Sun

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

Transcription:

ARRAYS CITS11

2 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 6 th Edition Chapter 5 in the 5 th and earlier Editions

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

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.

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

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

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;

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

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[5] occupied;

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 ; Array literals in this form can only be used in declarations. Related uses require new: numbers = new int[] { 3, 15, 4, 5 ; declaration, creation and initialization

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.

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.

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

Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling A Java example for loop version for(int hour = ; hour < hourcounts.length; hour++) { System.out.println(hour + ": " + hourcounts[hour]); while loop version int hour = ; 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 Practice Fill an array with the Fibonacci sequence. int[] fib = new int[1]; fib[] = ; fib[1] = 1; for... 1 1 2 3 5 8 13 21 34...

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 4. for(int num = 3; num < 4; num = num + 3) { System.out.println(num);

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

18 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 = ; index <= marks.length(); index++) { if (marks[index] > mean) { System.out.println(marks[index]);

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

21 USING ARRAYS More examples

22 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 2.8 23.4 Min 13.5 14.3 13.3 11.6 9.8 8.1 7.4 7.4 7.9 9. 1.6 12.3 Rain 28 25 29 66 12 14 126 14 81 8 46 24 PERTH AIRPORT Max 31.4 31.7 29.5 25.2 21.4 18.7 17.6 18.3 2. 22.3 25.4 28.5 Min 16.7 17.4 15.7 12.7 1.2 9. 8. 7.9 8.8 1.1 12.4 14.6 Rain 8 14 15 46 18 175 164 117 68 48 25 12

23 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

24 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 null a Only space for the array reference has been created, not for the array itself

25 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]; a An object is created that contains seven variables of type int The expression a.length can be used to refer to the size of a

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

27 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[] + 17; 7-1 15 17 a[] a[1] a[2] a[3] a[4] a[5] a[6]

28 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; 7 5 44 17 a[] a[1] a[2] a[3] a[4] a[5] a[6]

29 Summing the integers in an array private int sum(int[] a) { int sum=; 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

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

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

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

33 Find the index of the biggest integer private int max(int[] a) { int k = ; 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?

34 Returning an array Suppose we want to find the running sums of a sums({2,5, 8,3) = {2,7, 1,2 private int[] sums(int[] a) { int[] sums = new int[a.length]; sums[] = a[]; for (int i = 1; i < a.length; i++) { sums[i] = sums[i 1] + a[i]; return sums;

35 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 = ; i < a.length-1; i = i+2) { avs[i / 2] = (a[i] + a[i+1]) / 2; return avs;

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

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

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

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

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

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

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

43 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

44 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); System.out.println(x); 5 5 x is unchanged

45 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[] = 666; int[] x = {5,3,1; System.out.println(x[]); f(x); System.out.println(x[]); 5 666 x is unchanged but x[] is changed

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.

MORE ARRAYS CITS11

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

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

5 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 Declare the variable to refer to the array Create the space for the array elements using new Populate the array with objects by repeatedly using new, often in a loop

51 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

52 Creating a unit list Student[] unitlist; Declare unitlist = new Student[numStudents]; Create unitlist[] = new Student( 42371X,64); unitlist[1] = new Student( 499731,72); Populate unitlist[2] = new Student( 4127,55); unitlist[numstudents-1] = new Student( 41332,85);

53 The three steps unit null unit null null null null null unit[] unit[1] unit[2] unit[3] unit[4]

54 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[]; for (Student si : unitlist) if (si.getmark() > top.getmark()) top = si; return top;

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

56 Method signatures int max(int[] a) Student top(student[] unitlist)

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

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

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

6 What if we want to find the highest mark? private int highestmark(student[] unitlist) { int max = unitlist[].getmark(); for (Student si : unitlist) if (si.getmark() > max) max = si.getmark(); return max;

61 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();

62 2D arrays We sometimes need arrays with more than one dimension int[][] a = new int[4][3]; This creates an array with four rows and three columns The row index ranges from 3 and the column index from 2 a[][] a[1][] a[2][] a[3][] a[][1] a[1][1] a[2][1] a[3][1] a[][2] a[1][2] a[2][2] a[3][2]

63 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[] is a valid variable, representing the first row a[][2] is a valid variable, representing the last element in the first row

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

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

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

67 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 = ; i < a.length; i++) for (int j = ; j < a[i].length; j++) if (a[i][j]) return i; return -1;

68 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